FlatCAMApp.py 299 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. ############################################################
  8. import sys
  9. import traceback
  10. import urllib.request, urllib.parse, urllib.error
  11. import getopt
  12. import os
  13. import random
  14. import logging
  15. import simplejson as json
  16. import lzma
  17. import re
  18. import os
  19. from stat import S_IREAD, S_IRGRP, S_IROTH
  20. import subprocess
  21. import tkinter as tk
  22. from PyQt5 import QtCore, QtGui, QtWidgets, QtPrintSupport
  23. from PyQt5.QtCore import QSettings
  24. import time # Just used for debugging. Double check before removing.
  25. import urllib.request, urllib.parse, urllib.error
  26. import webbrowser
  27. from contextlib import contextmanager
  28. from xml.dom.minidom import parseString as parse_xml_string
  29. from copy import copy,deepcopy
  30. import numpy as np
  31. from datetime import datetime
  32. import gc
  33. ########################################
  34. ## Imports part of FlatCAM ##
  35. ########################################
  36. from ObjectCollection import *
  37. from FlatCAMObj import *
  38. from PlotCanvas import *
  39. from FlatCAMGUI import *
  40. from FlatCAMCommon import LoudDict
  41. from FlatCAMPostProc import load_postprocessors
  42. from FlatCAMEditor import FlatCAMGeoEditor, FlatCAMExcEditor
  43. from FlatCAMProcess import *
  44. from FlatCAMWorkerStack import WorkerStack
  45. from VisPyVisuals import Color
  46. from vispy.gloo.util import _screenshot
  47. from vispy.io import write_png
  48. from flatcamTools import *
  49. from multiprocessing import Pool
  50. import tclCommands
  51. # from ParseFont import *
  52. ########################################
  53. ## App ##
  54. ########################################
  55. class App(QtCore.QObject):
  56. """
  57. The main application class. The constructor starts the GUI.
  58. """
  59. # Get Cmd Line Options
  60. cmd_line_shellfile = ''
  61. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>"
  62. try:
  63. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  64. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=", "multiprocessing-fork="])
  65. except getopt.GetoptError:
  66. print(cmd_line_help)
  67. sys.exit(2)
  68. for opt, arg in cmd_line_options:
  69. if opt == '-h':
  70. print(cmd_line_help)
  71. sys.exit()
  72. elif opt == '--shellfile':
  73. cmd_line_shellfile = arg
  74. # Logging ##
  75. log = logging.getLogger('base')
  76. log.setLevel(logging.DEBUG)
  77. # log.setLevel(logging.WARNING)
  78. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  79. handler = logging.StreamHandler()
  80. handler.setFormatter(formatter)
  81. log.addHandler(handler)
  82. # Version
  83. version = 8.910
  84. version_date = "2019/02/23"
  85. beta = True
  86. # current date now
  87. date = str(datetime.today()).rpartition(' ')[0]
  88. # URL for update checks and statistics
  89. version_url = "http://flatcam.org/version"
  90. # App URL
  91. app_url = "http://flatcam.org"
  92. # Manual URL
  93. manual_url = "http://flatcam.org/manual/index.html"
  94. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  95. should_we_quit = True
  96. # this variable will hold the project status
  97. # if True it will mean that the project was modified and not saved
  98. should_we_save = False
  99. ##################
  100. ## Signals ##
  101. ##################
  102. # Inform the user
  103. # Handled by:
  104. # * App.info() --> Print on the status bar
  105. inform = QtCore.pyqtSignal(str)
  106. # General purpose background task
  107. worker_task = QtCore.pyqtSignal(dict)
  108. # File opened
  109. # Handled by:
  110. # * register_folder()
  111. # * register_recent()
  112. # Note: Setting the parameters to unicode does not seem
  113. # to have an effect. Then are received as Qstring
  114. # anyway.
  115. # File type and filename
  116. file_opened = QtCore.pyqtSignal(str, str)
  117. # File type and filename
  118. file_saved = QtCore.pyqtSignal(str, str)
  119. # Percentage of progress
  120. progress = QtCore.pyqtSignal(int)
  121. plots_updated = QtCore.pyqtSignal()
  122. # Emitted by new_object() and passes the new object as argument, plot flag.
  123. # on_object_created() adds the object to the collection, plots on appropriate flag
  124. # and emits new_object_available.
  125. object_created = QtCore.pyqtSignal(object, bool, bool)
  126. # Emitted when a object has been changed (like scaled, mirrored)
  127. object_changed = QtCore.pyqtSignal(object)
  128. # Emitted after object has been plotted.
  129. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  130. object_plotted = QtCore.pyqtSignal(object)
  131. # Emitted when a new object has been added to the collection
  132. # and is ready to be used.
  133. new_object_available = QtCore.pyqtSignal(object)
  134. message = QtCore.pyqtSignal(str, str, str)
  135. # Emmited when shell command is finished(one command only)
  136. shell_command_finished = QtCore.pyqtSignal(object)
  137. # Emitted when multiprocess pool has been recreated
  138. pool_recreated = QtCore.pyqtSignal(object)
  139. # Emitted when an unhandled exception happens
  140. # in the worker task.
  141. thread_exception = QtCore.pyqtSignal(object)
  142. def __init__(self, user_defaults=True, post_gui=None):
  143. """
  144. Starts the application.
  145. :return: app
  146. :rtype: App
  147. """
  148. App.log.info("FlatCAM Starting...")
  149. ###################
  150. ### OS-specific ###
  151. ###################
  152. # Folder for user settings.
  153. if sys.platform == 'win32':
  154. from win32com.shell import shell, shellcon
  155. if platform.architecture()[0] == '32bit':
  156. App.log.debug("Win32!")
  157. else:
  158. App.log.debug("Win64!")
  159. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + \
  160. '\FlatCAM'
  161. self.os = 'windows'
  162. else: # Linux/Unix/MacOS
  163. self.data_path = os.path.expanduser('~') + \
  164. '/.FlatCAM'
  165. self.os = 'unix'
  166. ###############################
  167. ### Setup folders and files ###
  168. ###############################
  169. if not os.path.exists(self.data_path):
  170. os.makedirs(self.data_path)
  171. App.log.debug('Created data folder: ' + self.data_path)
  172. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  173. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  174. self.postprocessorpaths = os.path.join(self.data_path,'postprocessors')
  175. if not os.path.exists(self.postprocessorpaths):
  176. os.makedirs(self.postprocessorpaths)
  177. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  178. # create current_defaults.FlatConfig file if there is none
  179. try:
  180. f = open(self.data_path + '/current_defaults.FlatConfig')
  181. f.close()
  182. except IOError:
  183. App.log.debug('Creating empty current_defaults.FlatConfig')
  184. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  185. json.dump({}, f)
  186. f.close()
  187. # create factory_defaults.FlatConfig file if there is none
  188. try:
  189. f = open(self.data_path + '/factory_defaults.FlatConfig')
  190. f.close()
  191. except IOError:
  192. App.log.debug('Creating empty factory_defaults.FlatConfig')
  193. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  194. json.dump({}, f)
  195. f.close()
  196. try:
  197. f = open(self.data_path + '/recent.json')
  198. f.close()
  199. except IOError:
  200. App.log.debug('Creating empty recent.json')
  201. f = open(self.data_path + '/recent.json', 'w')
  202. json.dump([], f)
  203. f.close()
  204. # Application directory. CHDIR to it. Otherwise, trying to load
  205. # GUI icons will fail as their path is relative.
  206. # This will fail under cx_freeze ...
  207. self.app_home = os.path.dirname(os.path.realpath(__file__))
  208. App.log.debug("Application path is " + self.app_home)
  209. App.log.debug("Started in " + os.getcwd())
  210. # cx_freeze workaround
  211. if os.path.isfile(self.app_home):
  212. self.app_home = os.path.dirname(self.app_home)
  213. os.chdir(self.app_home)
  214. # Create multiprocessing pool
  215. self.pool = Pool()
  216. # variable to store mouse coordinates
  217. self.mouse = [0, 0]
  218. ####################
  219. ## Initialize GUI ##
  220. ####################
  221. # FlatCAM colors used in plotting
  222. self.FC_light_green = '#BBF268BF'
  223. self.FC_dark_green = '#006E20BF'
  224. self.FC_light_blue = '#a5a5ffbf'
  225. self.FC_dark_blue = '#0000ffbf'
  226. QtCore.QObject.__init__(self)
  227. self.ui = FlatCAMGUI(self.version, self.beta, self)
  228. # self.connect(self.ui,
  229. # QtCore.SIGNAL("geomUpdate(int, int, int, int, int)"),
  230. # self.save_geometry) PyQt4
  231. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  232. self.ui.final_save.connect(self.final_save)
  233. ##############
  234. #### Data ####
  235. ##############
  236. self.recent = []
  237. self.clipboard = QtWidgets.QApplication.clipboard()
  238. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  239. self.project_filename = None
  240. self.toggle_units_ignore = False
  241. # self.defaults_form = PreferencesUI()
  242. self.general_defaults_form = GeneralPreferencesUI()
  243. self.gerber_defaults_form = GerberPreferencesUI()
  244. self.excellon_defaults_form = ExcellonPreferencesUI()
  245. self.geometry_defaults_form = GeometryPreferencesUI()
  246. self.cncjob_defaults_form = CNCJobPreferencesUI()
  247. self.tools_defaults_form = ToolsPreferencesUI()
  248. # when adding entries here read the comments in the method found bellow named:
  249. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  250. self.defaults_form_fields = {
  251. "units": self.general_defaults_form.general_app_group.units_radio,
  252. "global_shell_at_startup": self.general_defaults_form.general_app_group.shell_startup_cb,
  253. "global_version_check": self.general_defaults_form.general_app_group.version_check_cb,
  254. "global_send_stats": self.general_defaults_form.general_app_group.send_stats_cb,
  255. "global_project_at_startup": self.general_defaults_form.general_app_group.project_startup_cb,
  256. "global_project_autohide": self.general_defaults_form.general_app_group.project_autohide_cb,
  257. "global_app_level": self.general_defaults_form.general_app_group.app_level_radio,
  258. "global_compression_level": self.general_defaults_form.general_app_group.compress_combo,
  259. "global_save_compressed": self.general_defaults_form.general_app_group.save_type_cb,
  260. "global_gridx": self.general_defaults_form.general_gui_group.gridx_entry,
  261. "global_gridy": self.general_defaults_form.general_gui_group.gridy_entry,
  262. "global_snap_max": self.general_defaults_form.general_gui_group.snap_max_dist_entry,
  263. "global_plot_fill": self.general_defaults_form.general_gui_group.pf_color_entry,
  264. "global_plot_line": self.general_defaults_form.general_gui_group.pl_color_entry,
  265. "global_sel_fill": self.general_defaults_form.general_gui_group.sf_color_entry,
  266. "global_sel_line": self.general_defaults_form.general_gui_group.sl_color_entry,
  267. "global_alt_sel_fill": self.general_defaults_form.general_gui_group.alt_sf_color_entry,
  268. "global_alt_sel_line": self.general_defaults_form.general_gui_group.alt_sl_color_entry,
  269. "global_draw_color": self.general_defaults_form.general_gui_group.draw_color_entry,
  270. "global_sel_draw_color": self.general_defaults_form.general_gui_group.sel_draw_color_entry,
  271. "global_pan_button": self.general_defaults_form.general_app_group.pan_button_radio,
  272. "global_mselect_key": self.general_defaults_form.general_app_group.mselect_radio,
  273. # "global_pan_with_space_key": self.general_defaults_form.general_gui_group.pan_with_space_cb,
  274. "global_workspace": self.general_defaults_form.general_gui_group.workspace_cb,
  275. "global_workspaceT": self.general_defaults_form.general_gui_group.wk_cb,
  276. "gerber_plot": self.gerber_defaults_form.gerber_gen_group.plot_cb,
  277. "gerber_solid": self.gerber_defaults_form.gerber_gen_group.solid_cb,
  278. "gerber_multicolored": self.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  279. "gerber_circle_steps": self.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  280. "gerber_isotooldia": self.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  281. "gerber_isopasses": self.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  282. "gerber_isooverlap": self.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  283. "gerber_combine_passes": self.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  284. "gerber_milling_type": self.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  285. "gerber_noncoppermargin": self.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  286. "gerber_noncopperrounded": self.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  287. "gerber_bboxmargin": self.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  288. "gerber_bboxrounded": self.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  289. "excellon_plot": self.excellon_defaults_form.excellon_gen_group.plot_cb,
  290. "excellon_solid": self.excellon_defaults_form.excellon_gen_group.solid_cb,
  291. "excellon_format_upper_in": self.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  292. "excellon_format_lower_in": self.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  293. "excellon_format_upper_mm": self.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  294. "excellon_format_lower_mm": self.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  295. "excellon_zeros": self.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  296. "excellon_units": self.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  297. "excellon_optimization_type": self.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  298. "excellon_search_time": self.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  299. "excellon_offset": self.excellon_defaults_form.excellon_gen_group.offset_entry,
  300. "excellon_toolchangexy": self.excellon_defaults_form.excellon_gen_group.toolchangexy_entry,
  301. "excellon_startz": self.excellon_defaults_form.excellon_gen_group.estartz_entry,
  302. "excellon_endz": self.excellon_defaults_form.excellon_gen_group.eendz_entry,
  303. "excellon_feedrate_rapid": self.excellon_defaults_form.excellon_gen_group.feedrate_rapid_entry,
  304. "excellon_z_pdepth": self.excellon_defaults_form.excellon_gen_group.pdepth_entry,
  305. "excellon_feedrate_probe": self.excellon_defaults_form.excellon_gen_group.feedrate_probe_entry,
  306. "excellon_f_plunge": self.excellon_defaults_form.excellon_gen_group.fplunge_cb,
  307. "excellon_f_retract": self.excellon_defaults_form.excellon_gen_group.fretract_cb,
  308. "excellon_drillz": self.excellon_defaults_form.excellon_opt_group.cutz_entry,
  309. "excellon_travelz": self.excellon_defaults_form.excellon_opt_group.travelz_entry,
  310. "excellon_feedrate": self.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  311. "excellon_spindlespeed": self.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  312. "excellon_dwell": self.excellon_defaults_form.excellon_opt_group.dwell_cb,
  313. "excellon_dwelltime": self.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  314. "excellon_toolchange": self.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  315. "excellon_toolchangez": self.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  316. "excellon_ppname_e": self.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  317. "excellon_tooldia": self.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  318. "excellon_slot_tooldia": self.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  319. "excellon_gcode_type": self.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  320. "excellon_exp_units": self.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  321. "excellon_exp_format": self.excellon_defaults_form.excellon_exp_group.format_radio,
  322. "excellon_exp_integer": self.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  323. "excellon_exp_decimals": self.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  324. "excellon_exp_zeros": self.excellon_defaults_form.excellon_exp_group.zeros_radio,
  325. "geometry_plot": self.geometry_defaults_form.geometry_gen_group.plot_cb,
  326. "geometry_cnctooldia": self.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  327. "geometry_circle_steps": self.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  328. "geometry_segx": self.geometry_defaults_form.geometry_gen_group.segx_entry,
  329. "geometry_segy": self.geometry_defaults_form.geometry_gen_group.segy_entry,
  330. "geometry_feedrate_rapid": self.geometry_defaults_form.geometry_gen_group.cncfeedrate_rapid_entry,
  331. "geometry_feedrate_probe": self.geometry_defaults_form.geometry_gen_group.feedrate_probe_entry,
  332. "geometry_z_pdepth": self.geometry_defaults_form.geometry_gen_group.pdepth_entry,
  333. "geometry_f_plunge": self.geometry_defaults_form.geometry_gen_group.fplunge_cb,
  334. "geometry_toolchangexy": self.geometry_defaults_form.geometry_gen_group.toolchangexy_entry,
  335. "geometry_startz": self.geometry_defaults_form.geometry_gen_group.gstartz_entry,
  336. "geometry_endz": self.geometry_defaults_form.geometry_gen_group.gendz_entry,
  337. "geometry_extracut": self.geometry_defaults_form.geometry_gen_group.extracut_cb,
  338. "geometry_cutz": self.geometry_defaults_form.geometry_opt_group.cutz_entry,
  339. "geometry_travelz": self.geometry_defaults_form.geometry_opt_group.travelz_entry,
  340. "geometry_feedrate": self.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  341. "geometry_feedrate_z": self.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  342. "geometry_spindlespeed": self.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  343. "geometry_dwell": self.geometry_defaults_form.geometry_opt_group.dwell_cb,
  344. "geometry_dwelltime": self.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  345. "geometry_ppname_g": self.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  346. "geometry_toolchange": self.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  347. "geometry_toolchangez": self.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  348. "geometry_depthperpass": self.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  349. "geometry_multidepth": self.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  350. "cncjob_plot": self.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  351. "cncjob_plot_kind": self.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  352. "cncjob_tooldia": self.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  353. "cncjob_coords_decimals": self.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  354. "cncjob_fr_decimals": self.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  355. "cncjob_steps_per_circle": self.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  356. "cncjob_prepend": self.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  357. "cncjob_append": self.cncjob_defaults_form.cncjob_opt_group.append_text,
  358. "tools_ncctools": self.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  359. "tools_nccoverlap": self.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  360. "tools_nccmargin": self.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  361. "tools_nccmethod": self.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  362. "tools_nccconnect": self.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  363. "tools_ncccontour": self.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  364. "tools_nccrest": self.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  365. "tools_cutouttooldia": self.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  366. "tools_cutoutmargin": self.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  367. "tools_cutoutgapsize": self.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  368. "tools_gaps_rect": self.tools_defaults_form.tools_cutout_group.gaps_radio,
  369. "tools_gaps_ff": self.tools_defaults_form.tools_cutout_group.gaps_combo,
  370. "tools_painttooldia": self.tools_defaults_form.tools_paint_group.painttooldia_entry,
  371. "tools_paintoverlap": self.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  372. "tools_paintmargin": self.tools_defaults_form.tools_paint_group.paintmargin_entry,
  373. "tools_paintmethod": self.tools_defaults_form.tools_paint_group.paintmethod_combo,
  374. "tools_selectmethod": self.tools_defaults_form.tools_paint_group.selectmethod_combo,
  375. "tools_pathconnect": self.tools_defaults_form.tools_paint_group.pathconnect_cb,
  376. "tools_paintcontour": self.tools_defaults_form.tools_paint_group.contour_cb,
  377. "tools_2sided_mirror_axis": self.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  378. "tools_2sided_axis_loc": self.tools_defaults_form.tools_2sided_group.axis_location_radio,
  379. "tools_2sided_drilldia": self.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  380. "tools_film_type": self.tools_defaults_form.tools_film_group.film_type_radio,
  381. "tools_film_boundary": self.tools_defaults_form.tools_film_group.film_boundary_entry,
  382. "tools_film_scale": self.tools_defaults_form.tools_film_group.film_scale_entry,
  383. "tools_panelize_spacing_columns": self.tools_defaults_form.tools_panelize_group.pspacing_columns,
  384. "tools_panelize_spacing_rows": self.tools_defaults_form.tools_panelize_group.pspacing_rows,
  385. "tools_panelize_columns": self.tools_defaults_form.tools_panelize_group.pcolumns,
  386. "tools_panelize_rows": self.tools_defaults_form.tools_panelize_group.prows,
  387. "tools_panelize_constrain": self.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  388. "tools_panelize_constrainx": self.tools_defaults_form.tools_panelize_group.px_width_entry,
  389. "tools_panelize_constrainy": self.tools_defaults_form.tools_panelize_group.py_height_entry,
  390. "tools_panelize_panel_type": self.tools_defaults_form.tools_panelize_group.panel_type_radio,
  391. "tools_calc_vshape_tip_dia": self.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  392. "tools_calc_vshape_tip_angle": self.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  393. "tools_calc_vshape_cut_z": self.tools_defaults_form.tools_calculators_group.cut_z_entry,
  394. "tools_calc_electro_length": self.tools_defaults_form.tools_calculators_group.pcblength_entry,
  395. "tools_calc_electro_width": self.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  396. "tools_calc_electro_cdensity": self.tools_defaults_form.tools_calculators_group.cdensity_entry,
  397. "tools_calc_electro_growth": self.tools_defaults_form.tools_calculators_group.growth_entry,
  398. "tools_transform_rotate": self.tools_defaults_form.tools_transform_group.rotate_entry,
  399. "tools_transform_skew_x": self.tools_defaults_form.tools_transform_group.skewx_entry,
  400. "tools_transform_skew_y": self.tools_defaults_form.tools_transform_group.skewy_entry,
  401. "tools_transform_scale_x": self.tools_defaults_form.tools_transform_group.scalex_entry,
  402. "tools_transform_scale_y": self.tools_defaults_form.tools_transform_group.scaley_entry,
  403. "tools_transform_scale_link": self.tools_defaults_form.tools_transform_group.link_cb,
  404. "tools_transform_scale_reference": self.tools_defaults_form.tools_transform_group.reference_cb,
  405. "tools_transform_offset_x": self.tools_defaults_form.tools_transform_group.offx_entry,
  406. "tools_transform_offset_y": self.tools_defaults_form.tools_transform_group.offy_entry,
  407. "tools_transform_mirror_reference": self.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  408. "tools_transform_mirror_point": self.tools_defaults_form.tools_transform_group.flip_ref_entry,
  409. "tools_solderpaste_tools": self.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  410. "tools_solderpaste_new": self.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  411. "tools_solderpaste_z_start": self.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  412. "tools_solderpaste_z_dispense": self.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  413. "tools_solderpaste_z_stop": self.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  414. "tools_solderpaste_z_travel": self.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  415. "tools_solderpaste_z_toolchange": self.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  416. "tools_solderpaste_xy_toolchange": self.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  417. "tools_solderpaste_frxy": self.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  418. "tools_solderpaste_frz": self.tools_defaults_form.tools_solderpaste_group.frz_entry,
  419. "tools_solderpaste_frz_dispense": self.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  420. "tools_solderpaste_speedfwd": self.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  421. "tools_solderpaste_dwellfwd": self.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  422. "tools_solderpaste_speedrev": self.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  423. "tools_solderpaste_dwellrev": self.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  424. "tools_solderpaste_pp": self.tools_defaults_form.tools_solderpaste_group.pp_combo
  425. }
  426. #############################
  427. #### LOAD POSTPROCESSORS ####
  428. #############################
  429. self.postprocessors = load_postprocessors(self)
  430. for name in list(self.postprocessors.keys()):
  431. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  432. if name.partition('_')[0] == 'Paste':
  433. self.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  434. continue
  435. self.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  436. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  437. if name == 'hpgl':
  438. continue
  439. self.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  440. self.defaults = LoudDict()
  441. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  442. self.defaults.update({
  443. "global_serial": 0,
  444. "global_stats": {},
  445. "units": "IN",
  446. "global_version_check": True,
  447. "global_send_stats": True,
  448. "global_project_at_startup": False,
  449. "global_project_autohide": True,
  450. "global_app_level": 'b',
  451. "global_gridx": 1.0,
  452. "global_gridy": 1.0,
  453. "global_snap_max": 0.05,
  454. "global_grid_context_menu": {
  455. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  456. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  457. },
  458. "global_plot_fill": '#BBF268BF',
  459. "global_plot_line": '#006E20BF',
  460. "global_sel_fill": '#a5a5ffbf',
  461. "global_sel_line": '#0000ffbf',
  462. "global_alt_sel_fill": '#BBF268BF',
  463. "global_alt_sel_line": '#006E20BF',
  464. "global_draw_color": '#FF0000',
  465. "global_sel_draw_color": '#0000FF',
  466. "global_pan_button": '2',
  467. "global_mselect_key": 'Control',
  468. # "global_pan_with_space_key": False,
  469. "global_workspace": False,
  470. "global_workspaceT": "A4P",
  471. "global_toolbar_view": 127,
  472. "global_background_timeout": 300000, # Default value is 5 minutes
  473. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  474. # (python trace only for unknown errors),
  475. # 1 = show trace(show trace allways),
  476. # 2 = (For the future).
  477. # Persistence
  478. "global_last_folder": None,
  479. "global_last_save_folder": None,
  480. # Default window geometry
  481. "global_def_win_x": 100,
  482. "global_def_win_y": 100,
  483. "global_def_win_w": 1024,
  484. "global_def_win_h": 650,
  485. # Constants...
  486. "global_defaults_save_period_ms": 20000, # Time between default saves.
  487. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  488. "global_shell_at_startup": False, # Show the shell at startup.
  489. "global_recent_limit": 10, # Max. items in recent list.
  490. "global_compression_level": 3,
  491. "global_save_compressed": True,
  492. "fit_key": 'V',
  493. "zoom_out_key": '-',
  494. "zoom_in_key": '=',
  495. "grid_toggle_key": 'G',
  496. "zoom_ratio": 1.5,
  497. "global_point_clipboard_format": "(%.4f, %.4f)",
  498. "global_zdownrate": None,
  499. "gerber_plot": True,
  500. "gerber_solid": True,
  501. "gerber_multicolored": False,
  502. "gerber_isotooldia": 0.016,
  503. "gerber_isopasses": 1,
  504. "gerber_isooverlap": 0.15,
  505. "gerber_combine_passes": False,
  506. "gerber_milling_type": "cl",
  507. "gerber_noncoppermargin": 0.1,
  508. "gerber_noncopperrounded": False,
  509. "gerber_bboxmargin": 0.1,
  510. "gerber_bboxrounded": False,
  511. "gerber_circle_steps": 64,
  512. "gerber_use_buffer_for_union": True,
  513. "excellon_plot": True,
  514. "excellon_solid": True,
  515. "excellon_format_upper_in": 2,
  516. "excellon_format_lower_in": 4,
  517. "excellon_format_upper_mm": 3,
  518. "excellon_format_lower_mm": 3,
  519. "excellon_zeros": "L",
  520. "excellon_units": "INCH",
  521. "excellon_optimization_type": 'B',
  522. "excellon_search_time": 3,
  523. "excellon_drillz": -0.1,
  524. "excellon_travelz": 0.1,
  525. "excellon_feedrate": 3.0,
  526. "excellon_feedrate_rapid": 3.0,
  527. "excellon_feedrate_probe": 3.0,
  528. "excellon_spindlespeed": None,
  529. "excellon_dwell": False,
  530. "excellon_dwelltime": 1,
  531. "excellon_toolchange": False,
  532. "excellon_toolchangez": 1.0,
  533. "excellon_toolchangexy": "0.0, 0.0",
  534. "excellon_tooldia": 0.016,
  535. "excellon_offset": 0.0,
  536. "excellon_slot_tooldia": 0.016,
  537. "excellon_startz": None,
  538. "excellon_endz": 2.0,
  539. "excellon_ppname_e": 'default',
  540. "excellon_z_pdepth": -0.02,
  541. "excellon_f_plunge": False,
  542. "excellon_f_retract": False,
  543. "excellon_gcode_type": "drills",
  544. "excellon_exp_units": 'INCH',
  545. "excellon_exp_format": 'ndec',
  546. "excellon_exp_integer": 2,
  547. "excellon_exp_decimals": 4,
  548. "excellon_exp_zeros": 'LZ',
  549. "geometry_plot": True,
  550. "geometry_segx": 0.0,
  551. "geometry_segy": 0.0,
  552. "geometry_cutz": -0.002,
  553. "geometry_travelz": 0.1,
  554. "geometry_toolchange": False,
  555. "geometry_toolchangez": 1.0,
  556. "geometry_toolchangexy": "0.0, 0.0",
  557. "geometry_startz": None,
  558. "geometry_endz": 2.0,
  559. "geometry_feedrate": 3.0,
  560. "geometry_feedrate_z": 3.0,
  561. "geometry_feedrate_rapid": 3.0,
  562. "geometry_feedrate_probe": 3.0,
  563. "geometry_cnctooldia": 0.016,
  564. "geometry_spindlespeed": None,
  565. "geometry_dwell": False,
  566. "geometry_dwelltime": 1,
  567. "geometry_ppname_g": 'default',
  568. "geometry_z_pdepth": -0.02,
  569. "geometry_f_plunge": False,
  570. "geometry_depthperpass": 0.002,
  571. "geometry_multidepth": False,
  572. "geometry_extracut": False,
  573. "geometry_circle_steps": 64,
  574. "cncjob_plot": True,
  575. "cncjob_plot_kind": 'all',
  576. "cncjob_tooldia": 0.0393701,
  577. "cncjob_coords_decimals": 4,
  578. "cncjob_fr_decimals": 2,
  579. "cncjob_prepend": "",
  580. "cncjob_append": "",
  581. "cncjob_steps_per_circle": 64,
  582. "tools_ncctools": "1.0, 0.5",
  583. "tools_nccoverlap": 0.4,
  584. "tools_nccmargin": 0.1,
  585. "tools_nccmethod": "seed",
  586. "tools_nccconnect": True,
  587. "tools_ncccontour": True,
  588. "tools_nccrest": False,
  589. "tools_cutouttooldia": 0.1,
  590. "tools_cutoutmargin": 0.1,
  591. "tools_cutoutgapsize": 0.15,
  592. "tools_gaps_rect": "4",
  593. "tools_gaps_ff": "8",
  594. "tools_painttooldia": 0.07,
  595. "tools_paintoverlap": 0.15,
  596. "tools_paintmargin": 0.0,
  597. "tools_paintmethod": "seed",
  598. "tools_selectmethod": "single",
  599. "tools_pathconnect": True,
  600. "tools_paintcontour": True,
  601. "tools_2sided_mirror_axis": "X",
  602. "tools_2sided_axis_loc": "point",
  603. "tools_2sided_drilldia": 1,
  604. "tools_film_type": 'neg',
  605. "tools_film_boundary": 1,
  606. "tools_film_scale": 0,
  607. "tools_panelize_spacing_columns": 0,
  608. "tools_panelize_spacing_rows": 0,
  609. "tools_panelize_columns": 1,
  610. "tools_panelize_rows": 1,
  611. "tools_panelize_constrain": False,
  612. "tools_panelize_constrainx": 0.0,
  613. "tools_panelize_constrainy": 0.0,
  614. "tools_panelize_panel_type": 'gerber',
  615. "tools_calc_vshape_tip_dia": 0.007874,
  616. "tools_calc_vshape_tip_angle": 30,
  617. "tools_calc_vshape_cut_z": 0.000787,
  618. "tools_calc_electro_length": 10.0,
  619. "tools_calc_electro_width": 10.0,
  620. "tools_calc_electro_cdensity":13.0,
  621. "tools_calc_electro_growth": 10.0,
  622. "tools_transform_rotate": 90,
  623. "tools_transform_skew_x": 0.0,
  624. "tools_transform_skew_y": 0.0,
  625. "tools_transform_scale_x": 1.0,
  626. "tools_transform_scale_y": 1.0,
  627. "tools_transform_scale_link": True,
  628. "tools_transform_scale_reference": True,
  629. "tools_transform_offset_x": 0.0,
  630. "tools_transform_offset_y": 0.0,
  631. "tools_transform_mirror_reference": False,
  632. "tools_transform_mirror_point": (0, 0),
  633. "tools_solderpaste_tools": "1.0, 0.3",
  634. "tools_solderpaste_new": 0.3,
  635. "tools_solderpaste_z_start": 0.005,
  636. "tools_solderpaste_z_dispense": 0.01,
  637. "tools_solderpaste_z_stop": 0.005,
  638. "tools_solderpaste_z_travel": 0.1,
  639. "tools_solderpaste_z_toolchange": 1.0,
  640. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  641. "tools_solderpaste_frxy": 3.0,
  642. "tools_solderpaste_frz": 3.0,
  643. "tools_solderpaste_frz_dispense": 1.0,
  644. "tools_solderpaste_speedfwd": 20,
  645. "tools_solderpaste_dwellfwd": 1,
  646. "tools_solderpaste_speedrev": 10,
  647. "tools_solderpaste_dwellrev": 1,
  648. "tools_solderpaste_pp": 'Paste_1'
  649. })
  650. ###############################
  651. ### Load defaults from file ###
  652. if user_defaults:
  653. self.load_defaults(filename='current_defaults')
  654. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  655. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  656. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  657. self.save_defaults(silent=True)
  658. self.propagate_defaults(silent=True)
  659. self.restore_main_win_geom()
  660. def auto_save_defaults():
  661. try:
  662. self.save_defaults(silent=True)
  663. self.propagate_defaults(silent=True)
  664. finally:
  665. QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  666. # the following lines activates automatic defaults save
  667. # if user_defaults:
  668. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  669. # self.options_form = PreferencesUI()
  670. self.general_options_form = GeneralPreferencesUI()
  671. self.gerber_options_form = GerberPreferencesUI()
  672. self.excellon_options_form = ExcellonPreferencesUI()
  673. self.geometry_options_form = GeometryPreferencesUI()
  674. self.cncjob_options_form = CNCJobPreferencesUI()
  675. self.tools_options_form = ToolsPreferencesUI()
  676. self.options_form_fields = {
  677. "units": self.general_options_form.general_app_group.units_radio,
  678. "global_gridx": self.general_options_form.general_gui_group.gridx_entry,
  679. "global_gridy": self.general_options_form.general_gui_group.gridy_entry,
  680. "global_snap_max": self.general_options_form.general_gui_group.snap_max_dist_entry,
  681. "gerber_plot": self.gerber_options_form.gerber_gen_group.plot_cb,
  682. "gerber_solid": self.gerber_options_form.gerber_gen_group.solid_cb,
  683. "gerber_multicolored": self.gerber_options_form.gerber_gen_group.multicolored_cb,
  684. "gerber_isotooldia": self.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  685. "gerber_isopasses": self.gerber_options_form.gerber_opt_group.iso_width_entry,
  686. "gerber_isooverlap": self.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  687. "gerber_combine_passes": self.gerber_options_form.gerber_opt_group.combine_passes_cb,
  688. "gerber_noncoppermargin": self.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  689. "gerber_noncopperrounded": self.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  690. "gerber_bboxmargin": self.gerber_options_form.gerber_opt_group.bbmargin_entry,
  691. "gerber_bboxrounded": self.gerber_options_form.gerber_opt_group.bbrounded_cb,
  692. "excellon_plot": self.excellon_options_form.excellon_gen_group.plot_cb,
  693. "excellon_solid": self.excellon_options_form.excellon_gen_group.solid_cb,
  694. "excellon_format_upper_in": self.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  695. "excellon_format_lower_in": self.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  696. "excellon_format_upper_mm": self.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  697. "excellon_format_lower_mm": self.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  698. "excellon_zeros": self.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  699. "excellon_units": self.excellon_options_form.excellon_gen_group.excellon_units_radio,
  700. "excellon_optimization_type": self.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  701. "excellon_feedrate_rapid": self.excellon_options_form.excellon_gen_group.feedrate_rapid_entry,
  702. "excellon_toolchangexy": self.excellon_options_form.excellon_gen_group.toolchangexy_entry,
  703. "excellon_f_plunge": self.excellon_options_form.excellon_gen_group.fplunge_cb,
  704. "excellon_startz": self.excellon_options_form.excellon_gen_group.estartz_entry,
  705. "excellon_endz": self.excellon_options_form.excellon_gen_group.eendz_entry,
  706. "excellon_drillz": self.excellon_options_form.excellon_opt_group.cutz_entry,
  707. "excellon_travelz": self.excellon_options_form.excellon_opt_group.travelz_entry,
  708. "excellon_feedrate": self.excellon_options_form.excellon_opt_group.feedrate_entry,
  709. "excellon_spindlespeed": self.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  710. "excellon_dwell": self.excellon_options_form.excellon_opt_group.dwell_cb,
  711. "excellon_dwelltime": self.excellon_options_form.excellon_opt_group.dwelltime_entry,
  712. "excellon_toolchange": self.excellon_options_form.excellon_opt_group.toolchange_cb,
  713. "excellon_toolchangez": self.excellon_options_form.excellon_opt_group.toolchangez_entry,
  714. "excellon_tooldia": self.excellon_options_form.excellon_opt_group.tooldia_entry,
  715. "excellon_ppname_e": self.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  716. "geometry_plot": self.geometry_options_form.geometry_gen_group.plot_cb,
  717. "geometry_cnctooldia": self.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  718. "geometry_segx": self.geometry_options_form.geometry_gen_group.segx_entry,
  719. "geometry_segy": self.geometry_options_form.geometry_gen_group.segy_entry,
  720. "geometry_feedrate_rapid": self.geometry_options_form.geometry_gen_group.cncfeedrate_rapid_entry,
  721. "geometry_f_plunge": self.geometry_options_form.geometry_gen_group.fplunge_cb,
  722. "geometry_toolchangexy": self.geometry_options_form.geometry_gen_group.toolchangexy_entry,
  723. "geometry_startz": self.geometry_options_form.geometry_gen_group.gstartz_entry,
  724. "geometry_endz": self.geometry_options_form.geometry_gen_group.gendz_entry,
  725. "geometry_extracut": self.geometry_options_form.geometry_gen_group.extracut_cb,
  726. "geometry_cutz": self.geometry_options_form.geometry_opt_group.cutz_entry,
  727. "geometry_travelz": self.geometry_options_form.geometry_opt_group.travelz_entry,
  728. "geometry_feedrate": self.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  729. "geometry_feedrate_z": self.geometry_options_form.geometry_opt_group.cncplunge_entry,
  730. "geometry_spindlespeed": self.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  731. "geometry_dwell": self.geometry_options_form.geometry_opt_group.dwell_cb,
  732. "geometry_dwelltime": self.geometry_options_form.geometry_opt_group.dwelltime_entry,
  733. "geometry_ppname_g": self.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  734. "geometry_toolchange": self.geometry_options_form.geometry_opt_group.toolchange_cb,
  735. "geometry_toolchangez": self.geometry_options_form.geometry_opt_group.toolchangez_entry,
  736. "geometry_depthperpass": self.geometry_options_form.geometry_opt_group.depthperpass_entry,
  737. "geometry_multidepth": self.geometry_options_form.geometry_opt_group.multidepth_cb,
  738. "cncjob_plot": self.cncjob_options_form.cncjob_gen_group.plot_cb,
  739. "cncjob_tooldia": self.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  740. "cncjob_prepend": self.cncjob_options_form.cncjob_opt_group.prepend_text,
  741. "cncjob_append": self.cncjob_options_form.cncjob_opt_group.append_text,
  742. "tools_ncctools": self.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  743. "tools_nccoverlap": self.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  744. "tools_nccmargin": self.tools_options_form.tools_ncc_group.ncc_margin_entry,
  745. "tools_cutouttooldia": self.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  746. "tools_cutoutmargin": self.tools_options_form.tools_cutout_group.cutout_margin_entry,
  747. "tools_cutoutgapsize": self.tools_options_form.tools_cutout_group.cutout_gap_entry,
  748. "tools_gaps_rect": self.tools_options_form.tools_cutout_group.gaps_radio,
  749. "tools_gaps_ff": self.tools_options_form.tools_cutout_group.gaps_combo,
  750. "tools_painttooldia": self.tools_options_form.tools_paint_group.painttooldia_entry,
  751. "tools_paintoverlap": self.tools_options_form.tools_paint_group.paintoverlap_entry,
  752. "tools_paintmargin": self.tools_options_form.tools_paint_group.paintmargin_entry,
  753. "tools_paintmethod": self.tools_options_form.tools_paint_group.paintmethod_combo,
  754. "tools_selectmethod": self.tools_options_form.tools_paint_group.selectmethod_combo,
  755. "tools_pathconnect": self.tools_options_form.tools_paint_group.pathconnect_cb,
  756. "tools_paintcontour": self.tools_options_form.tools_paint_group.contour_cb,
  757. "tools_2sided_mirror_axis": self.tools_options_form.tools_2sided_group.mirror_axis_radio,
  758. "tools_2sided_axis_loc": self.tools_options_form.tools_2sided_group.axis_location_radio,
  759. "tools_2sided_drilldia": self.tools_options_form.tools_2sided_group.drill_dia_entry,
  760. "tools_film_type": self.tools_options_form.tools_film_group.film_type_radio,
  761. "tools_film_boundary": self.tools_options_form.tools_film_group.film_boundary_entry,
  762. "tools_film_scale": self.tools_options_form.tools_film_group.film_scale_entry,
  763. "tools_panelize_spacing_columns": self.tools_options_form.tools_panelize_group.pspacing_columns,
  764. "tools_panelize_spacing_rows": self.tools_options_form.tools_panelize_group.pspacing_rows,
  765. "tools_panelize_columns": self.tools_options_form.tools_panelize_group.pcolumns,
  766. "tools_panelize_rows": self.tools_options_form.tools_panelize_group.prows,
  767. "tools_panelize_constrain": self.tools_options_form.tools_panelize_group.pconstrain_cb,
  768. "tools_panelize_constrainx": self.tools_options_form.tools_panelize_group.px_width_entry,
  769. "tools_panelize_constrainy": self.tools_options_form.tools_panelize_group.py_height_entry
  770. }
  771. for name in list(self.postprocessors.keys()):
  772. self.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  773. self.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  774. self.options = LoudDict()
  775. self.options.set_change_callback(self.on_options_dict_change)
  776. self.options.update({
  777. "units": "IN",
  778. "global_gridx": 1.0,
  779. "global_gridy": 1.0,
  780. "global_snap_max": 0.05,
  781. "global_background_timeout": 300000, # Default value is 5 minutes
  782. "global_verbose_error_level": 0, # Shell verbosity:
  783. # 0 = default(python trace only for unknown errors),
  784. # 1 = show trace(show trace allways), 2 = (For the future).
  785. "gerber_plot": True,
  786. "gerber_solid": True,
  787. "gerber_multicolored": False,
  788. "gerber_isotooldia": 0.016,
  789. "gerber_isopasses": 1,
  790. "gerber_isooverlap": 0.15,
  791. "gerber_combine_passes": True,
  792. "gerber_noncoppermargin": 0.0,
  793. "gerber_noncopperrounded": False,
  794. "gerber_bboxmargin": 0.0,
  795. "gerber_bboxrounded": False,
  796. "excellon_plot": True,
  797. "excellon_solid": False,
  798. "excellon_format_upper_in": 2,
  799. "excellon_format_lower_in": 4,
  800. "excellon_format_upper_mm": 3,
  801. "excellon_format_lower_mm": 3,
  802. "excellon_units": 'INCH',
  803. "excellon_optimization_type": 'B',
  804. "excellon_search_time": 3,
  805. "excellon_zeros": "L",
  806. "excellon_drillz": -0.1,
  807. "excellon_travelz": 0.1,
  808. "excellon_feedrate": 3.0,
  809. "excellon_feedrate_rapid": 3.0,
  810. "excellon_spindlespeed": None,
  811. "excellon_dwell": True,
  812. "excellon_dwelltime": 1000,
  813. "excellon_toolchange": False,
  814. "excellon_toolchangez": 1.0,
  815. "excellon_toolchangexy": "0.0, 0.0",
  816. "excellon_tooldia": 0.016,
  817. "excellon_ppname_e": 'default',
  818. "excellon_f_plunge": False,
  819. "excellon_startz": None,
  820. "excellon_endz": 2.0,
  821. "geometry_plot": True,
  822. "geometry_segx": 0.0,
  823. "geometry_segy": 0.0,
  824. "geometry_cutz": -0.002,
  825. "geometry_travelz": 0.1,
  826. "geometry_feedrate": 3.0,
  827. "geometry_feedrate_z": 3.0,
  828. "geometry_feedrate_rapid": 3.0,
  829. "geometry_spindlespeed": None,
  830. "geometry_dwell": True,
  831. "geometry_dwelltime": 1000,
  832. "geometry_cnctooldia": 0.016,
  833. "geometry_toolchange": False,
  834. "geometry_toolchangez": 2.0,
  835. "geometry_toolchangexy": "0.0, 0.0",
  836. "geometry_startz": None,
  837. "geometry_endz": 2.0,
  838. "geometry_ppname_g": "default",
  839. "geometry_f_plunge": False,
  840. "geometry_depthperpass": 0.002,
  841. "geometry_multidepth": False,
  842. "geometry_extracut": False,
  843. "cncjob_plot": True,
  844. "cncjob_tooldia": 0.016,
  845. "cncjob_prepend": "",
  846. "cncjob_append": "",
  847. "tools_ncctools": "1.0, 0.5",
  848. "tools_nccoverlap": 0.4,
  849. "tools_nccmargin": 1,
  850. "tools_cutouttooldia": 0.07,
  851. "tools_cutoutmargin": 0.1,
  852. "tools_cutoutgapsize": 0.15,
  853. "tools_gaps_rect": "4",
  854. "tools_gaps_ff": "8",
  855. "tools_painttooldia": 0.07,
  856. "tools_paintoverlap": 0.15,
  857. "tools_paintmargin": 0.0,
  858. "tools_paintmethod": "seed",
  859. "tools_selectmethod": "single",
  860. "tools_pathconnect": True,
  861. "tools_paintcontour": True,
  862. "tools_2sided_mirror_axis": "X",
  863. "tools_2sided_axis_loc": 'point',
  864. "tools_2sided_drilldia": 1,
  865. "tools_film_type": 'neg',
  866. "tools_film_boundary": 1,
  867. "tools_film_scale": 0,
  868. "tools_panelize_spacing_columns": 0,
  869. "tools_panelize_spacing_rows": 0,
  870. "tools_panelize_columns": 1,
  871. "tools_panelize_rows": 1,
  872. "tools_panelize_constrain": False,
  873. "tools_panelize_constrainx": 0.0,
  874. "tools_panelize_constrainy": 0.0
  875. })
  876. self.options.update(self.defaults) # Copy app defaults to project options
  877. self.gen_form = None
  878. self.ger_form = None
  879. self.exc_form = None
  880. self.geo_form = None
  881. self.cnc_form = None
  882. self.tools_form = None
  883. self.on_options_combo_change(0) # Will show the initial form
  884. ### Define OBJECT COLLECTION ###
  885. self.collection = ObjectCollection(self)
  886. self.ui.project_tab_layout.addWidget(self.collection.view)
  887. ###
  888. self.log.debug("Finished creating Object Collection.")
  889. ### Initialize the color box's color in Preferences -> Global -> Color
  890. # Init Plot Colors
  891. self.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  892. self.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  893. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  894. self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  895. int(self.defaults['global_plot_fill'][7:9], 16))
  896. self.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  897. int(self.defaults['global_plot_fill'][7:9], 16))
  898. self.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  899. self.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  900. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  901. # Init Left-Right Selection colors
  902. self.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  903. self.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  904. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  905. self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  906. int(self.defaults['global_sel_fill'][7:9], 16))
  907. self.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  908. int(self.defaults['global_sel_fill'][7:9], 16))
  909. self.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  910. self.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  911. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  912. # Init Right-Left Selection colors
  913. self.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(self.defaults['global_alt_sel_fill'])
  914. self.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  915. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  916. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  917. int(self.defaults['global_sel_fill'][7:9], 16))
  918. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  919. int(self.defaults['global_sel_fill'][7:9], 16))
  920. self.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(self.defaults['global_alt_sel_line'])
  921. self.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  922. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  923. # Init Draw color and Selection Draw Color
  924. self.general_defaults_form.general_gui_group.draw_color_entry.set_value(self.defaults['global_draw_color'])
  925. self.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  926. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  927. self.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(self.defaults['global_sel_draw_color'])
  928. self.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  929. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  930. #### End of Data ####
  931. #### Plot Area ####
  932. start_plot_time = time.time() # debug
  933. self.plotcanvas = PlotCanvas(self.ui.right_layout, self)
  934. self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
  935. self.plotcanvas.vis_connect('mouse_press', self.on_mouse_click_over_plot)
  936. self.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release_over_plot)
  937. self.plotcanvas.vis_connect('mouse_double_click', self.on_double_click_over_plot)
  938. # Keys over plot enabled
  939. self.plotcanvas.vis_connect('key_press', self.ui.keyPressEvent)
  940. self.ui.splitter.setStretchFactor(1, 2)
  941. # So it can receive key presses
  942. self.plotcanvas.vispy_canvas.native.setFocus()
  943. self.app_cursor = self.plotcanvas.new_cursor()
  944. self.app_cursor.enabled = False
  945. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  946. # depending on from where those tools are called different actions can be done
  947. self.call_source = 'app'
  948. end_plot_time = time.time()
  949. self.log.debug("Finished Canvas initialization in %s seconds." % (str(end_plot_time - start_plot_time)))
  950. ### EDITOR section
  951. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  952. self.exc_editor = FlatCAMExcEditor(self)
  953. #### Adjust tabs width ####
  954. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  955. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  956. self.collection.view.setMinimumWidth(290)
  957. self.log.debug("Finished adding Geometry and Excellon Editor's.")
  958. #### Worker ####
  959. self.workers = WorkerStack()
  960. self.worker_task.connect(self.workers.add_task)
  961. ### Signal handling ###
  962. ## Custom signals
  963. self.inform.connect(self.info)
  964. self.message.connect(self.message_dialog)
  965. self.progress.connect(self.set_progress_bar)
  966. self.object_created.connect(self.on_object_created)
  967. self.object_changed.connect(self.on_object_changed)
  968. self.object_plotted.connect(self.on_object_plotted)
  969. self.plots_updated.connect(self.on_plots_updated)
  970. self.file_opened.connect(self.register_recent)
  971. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  972. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  973. ## Standard signals
  974. # Menu
  975. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  976. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  977. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  978. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  979. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  980. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  981. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  982. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  983. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  984. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  985. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  986. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  987. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  988. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  989. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  990. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  991. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  992. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  993. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  994. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  995. self.ui.menufile_exit.triggered.connect(self.on_app_exit)
  996. self.ui.menueditedit.triggered.connect(self.object2editor)
  997. self.ui.menueditok.triggered.connect(self.editor2object)
  998. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  999. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1000. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1001. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1002. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1003. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1004. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1005. self.ui.menueditcopyobjectasgeom.triggered.connect(self.on_copy_object_as_geometry)
  1006. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1007. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1008. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1009. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1010. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1011. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1012. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1013. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1014. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1015. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1016. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1017. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1018. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1019. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1020. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1021. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1022. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1023. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1024. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1025. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1026. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1027. self.ui.menuview_zoom_in.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1028. self.ui.menuview_zoom_out.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1029. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1030. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1031. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1032. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1033. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1034. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1035. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1036. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1037. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  1038. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1039. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1040. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1041. self.ui.menuprojectenable.triggered.connect(lambda: self.enable_plots(self.collection.get_selected()))
  1042. self.ui.menuprojectdisable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
  1043. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1044. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1045. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1046. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1047. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1048. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1049. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1050. # Toolbar
  1051. #self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1052. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1053. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1054. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1055. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1056. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1057. self.ui.replot_btn.triggered.connect(self.plot_all)
  1058. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1059. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1060. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1061. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  1062. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  1063. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1064. self.ui.update_obj_btn.triggered.connect(self.editor2object)
  1065. self.ui.delete_btn.triggered.connect(self.on_delete)
  1066. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  1067. # Context Menu
  1068. self.ui.popmenu_disable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
  1069. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1070. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1071. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1072. self.ui.draw_line.triggered.connect(self.geo_editor.draw_tool_path)
  1073. self.ui.draw_rect.triggered.connect(self.geo_editor.draw_tool_rectangle)
  1074. self.ui.draw_cut.triggered.connect(self.geo_editor.cutpath)
  1075. self.ui.draw_move.triggered.connect(self.geo_editor.on_move)
  1076. self.ui.drill.triggered.connect(self.exc_editor.exc_add_drill)
  1077. self.ui.drill_array.triggered.connect(self.exc_editor.exc_add_drill_array)
  1078. self.ui.drill_copy.triggered.connect(self.exc_editor.exc_copy_drills)
  1079. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1080. self.ui.clearplot.triggered.connect(self.clear_plots)
  1081. self.ui.replot.triggered.connect(self.plot_all)
  1082. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1083. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1084. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1085. self.ui.popmenu_save.triggered.connect(self.editor2object)
  1086. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1087. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1088. # Preferences Plot Area TAB
  1089. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1090. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1091. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1092. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1093. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1094. ###############################
  1095. ### GUI PREFERENCES SIGNALS ###
  1096. ###############################
  1097. self.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1098. self.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(self.on_language_apply)
  1099. ###############################
  1100. ### GUI PREFERENCES SIGNALS ###
  1101. ###############################
  1102. # Setting plot colors signals
  1103. self.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(self.on_pf_color_entry)
  1104. self.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(self.on_pf_color_button)
  1105. self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(self.on_pf_color_spinner)
  1106. self.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(self.on_pf_color_slider)
  1107. self.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(self.on_pl_color_entry)
  1108. self.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(self.on_pl_color_button)
  1109. # Setting selection (left - right) colors signals
  1110. self.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(self.on_sf_color_entry)
  1111. self.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(self.on_sf_color_button)
  1112. self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(self.on_sf_color_spinner)
  1113. self.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(self.on_sf_color_slider)
  1114. self.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(self.on_sl_color_entry)
  1115. self.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(self.on_sl_color_button)
  1116. # Setting selection (right - left) colors signals
  1117. self.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(self.on_alt_sf_color_entry)
  1118. self.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(self.on_alt_sf_color_button)
  1119. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1120. self.on_alt_sf_color_spinner)
  1121. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1122. self.on_alt_sf_color_slider)
  1123. self.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(self.on_alt_sl_color_entry)
  1124. self.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(self.on_alt_sl_color_button)
  1125. # Setting Editor Draw colors signals
  1126. self.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(self.on_draw_color_entry)
  1127. self.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(self.on_draw_color_button)
  1128. self.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(self.on_sel_draw_color_entry)
  1129. self.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(self.on_sel_draw_color_button)
  1130. self.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1131. self.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1132. self.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1133. # Modify G-CODE Plot Area TAB
  1134. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  1135. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  1136. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  1137. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  1138. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  1139. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  1140. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  1141. # Object list
  1142. self.collection.view.activated.connect(self.on_row_activated)
  1143. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1144. self.general_defaults_form.general_app_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1145. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1146. self.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1147. self.on_excellon_defaults_button)
  1148. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1149. self.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1150. self.on_excellon_options_button)
  1151. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1152. self.tool_tab_locked = False
  1153. # decide if to show or hide the Notebook side of the screen at startup
  1154. if self.defaults["global_project_at_startup"] is True:
  1155. self.ui.splitter.setSizes([1, 1])
  1156. else:
  1157. self.ui.splitter.setSizes([0, 1])
  1158. ####################
  1159. ### Other setups ###
  1160. ####################
  1161. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1162. self.setup_obj_classes()
  1163. self.setup_recent_items()
  1164. self.setup_component_editor()
  1165. #############
  1166. ### Shell ###
  1167. #############
  1168. ###
  1169. # Auto-complete KEYWORDS
  1170. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1171. 'aligndrill', 'clear',
  1172. 'aligndrillgrid', 'cncjob', 'cutout', 'delete', 'drillcncjob',
  1173. 'export_gcode',
  1174. 'export_svg', 'ext', 'exteriors', 'follow', 'geo_union', 'geocutout', 'get_names',
  1175. 'get_sys', 'getsys', 'help', 'import_svg', 'interiors', 'isolate', 'join_excellon',
  1176. 'join_excellons', 'join_geometries', 'join_geometry', 'list_sys', 'listsys', 'mill',
  1177. 'millholes', 'mirror', 'new', 'new_geometry', 'offset', 'open_excellon', 'open_gcode',
  1178. 'open_gerber', 'open_project', 'options', 'paint', 'pan', 'panel', 'panelize', 'plot',
  1179. 'save', 'save_project', 'save_sys', 'scale', 'set_active', 'set_sys', 'setsys',
  1180. 'skew', 'subtract_poly', 'subtract_rectangle', 'version', 'write_gcode'
  1181. ]
  1182. self.ordinary_keywords = ['name', 'center_x', 'center_y', 'radius', 'x0', 'y0', 'x1', 'y1', 'box', 'axis',
  1183. 'holes','grid', 'minoffset', 'gridoffset','axisoffset', 'dia', 'dist', 'gridoffsetx',
  1184. 'gridoffsety', 'columns', 'rows', 'z_cut', 'z_move', 'feedrate', 'feedrate_rapid',
  1185. 'tooldia', 'multidepth', 'extracut', 'depthperpass', 'ppname_g', 'outname', 'margin',
  1186. 'gaps', 'gapsize', 'tools', 'drillz', 'travelz', 'spindlespeed', 'toolchange',
  1187. 'toolchangez', 'endz', 'ppname_e', 'opt_type', 'preamble', 'postamble', 'filename',
  1188. 'scale_factor', 'type', 'passes', 'overlap', 'combine', 'use_threads', 'x', 'y',
  1189. 'follow', 'all', 'spacing_columns', 'spacing_rows', 'factor', 'value', 'angle_x',
  1190. 'angle_y', 'gridx', 'gridy', 'True', 'False'
  1191. ]
  1192. self.myKeywords = self.tcl_commands_list + self.ordinary_keywords
  1193. self.shell = FCShell(self, version=self.version)
  1194. self.shell._edit.set_model_data(self.myKeywords)
  1195. self.shell.setWindowIcon(self.ui.app_icon)
  1196. self.shell.setWindowTitle("FlatCAM Shell")
  1197. self.shell.resize(*self.defaults["global_shell_shape"])
  1198. self.shell.append_output("FlatCAM %s (c)2014-2019 Juan Pablo Caram " % self.version)
  1199. self.shell.append_output("(Type help to get started)\n\n")
  1200. self.init_tcl()
  1201. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1202. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  1203. self.ui.shell_dock.setWidget(self.shell)
  1204. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1205. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1206. QtWidgets.QDockWidget.DockWidgetFloatable |
  1207. QtWidgets.QDockWidget.DockWidgetClosable)
  1208. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1209. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1210. if self.defaults["global_shell_at_startup"]:
  1211. self.ui.shell_dock.show()
  1212. else:
  1213. self.ui.shell_dock.hide()
  1214. #########################
  1215. ### Tools and Plugins ###
  1216. #########################
  1217. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1218. self.install_tools()
  1219. ### System Font Parsing ###
  1220. # self.f_parse = ParseFont(self)
  1221. # self.parse_system_fonts()
  1222. # test if the program was started with a script as parameter
  1223. if self.cmd_line_shellfile:
  1224. try:
  1225. with open(self.cmd_line_shellfile, "r") as myfile:
  1226. cmd_line_shellfile_text = myfile.read()
  1227. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  1228. except Exception as ext:
  1229. print("ERROR: ", ext)
  1230. sys.exit(2)
  1231. ###########################
  1232. #### Check for updates ####
  1233. ###########################
  1234. # Separate thread (Not worker)
  1235. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1236. if (self.beta is False or self.beta is None) and \
  1237. self.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  1238. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1239. self.thr2 = QtCore.QThread()
  1240. self.worker_task.emit({'fcn': self.version_check,
  1241. 'params': []})
  1242. self.thr2.start()
  1243. ####################################
  1244. #### Variables for global usage ####
  1245. ####################################
  1246. # coordinates for relative position display
  1247. self.rel_point1 = (0, 0)
  1248. self.rel_point2 = (0, 0)
  1249. # variable to store coordinates
  1250. self.pos = (0, 0)
  1251. self.pos_jump = (0, 0)
  1252. # variable to store if there was motion before right mouse button click (panning)
  1253. self.panning_action = False
  1254. # variable to store if a command is active (then the var is not None) and which one it is
  1255. self.command_active = None
  1256. # variable to store the status of moving selection action
  1257. # None value means that it's not an selection action
  1258. # True value = a selection from left to right
  1259. # False value = a selection from right to left
  1260. self.selection_type = None
  1261. # List to store the objects that are currently loaded in FlatCAM
  1262. # This list is updated on each object creation or object delete
  1263. self.all_objects_list = []
  1264. # List to store the objects that are selected
  1265. self.sel_objects_list = []
  1266. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1267. self.key_modifiers = None
  1268. # Variable to hold the status of the axis
  1269. self.toggle_axis = True
  1270. # Variable to store the status of the fullscreen event
  1271. self.toggle_fscreen = False
  1272. self.cursor = None
  1273. # Variable to store the GCODE that was edited
  1274. self.gcode_edited = ""
  1275. self.grb_list = ['gbr', 'ger', 'gtl', 'gbl', 'gts', 'gbs', 'gtp', 'gbp', 'gto', 'gbo', 'gm1', 'gm2', 'gm3', 'gko',
  1276. 'cmp', 'sol', 'stc', 'sts', 'plc', 'pls', 'crc', 'crs', 'tsm', 'bsm', 'ly2', 'ly15', 'dim', 'mil',
  1277. 'grb', 'top', 'bot', 'smt', 'smb', 'sst', 'ssb', 'spt', 'spb', 'pho', 'gdo', 'art', 'gbd']
  1278. self.exc_list = ['drl', 'txt', 'xln', 'drd', 'tap', 'exc']
  1279. self.gcode_list = ['nc', 'ncc', 'tap', 'gcode', 'cnc', 'ecs', 'fnc', 'dnc', 'ncg', 'gc', 'fan', 'fgc', 'din',
  1280. 'xpi', 'hnc', 'h', 'i', 'ncp', 'min', 'gcd', 'rol', 'mpr', 'ply', 'out', 'eia', 'plt', 'sbp',
  1281. 'mpf']
  1282. self.svg_list = ['svg']
  1283. self.dxf_list = ['dxf']
  1284. self.prj_list = ['flatprj']
  1285. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1286. # flag for polygons not cleared
  1287. self.poly_not_cleared = False
  1288. ### Save defaults to factory_defaults.FlatConfig file ###
  1289. ### It's done only once after install #############
  1290. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  1291. fac_def_from_file = factory_file.read()
  1292. factory_defaults = json.loads(fac_def_from_file)
  1293. # if the file contain an empty dictionary then save the factory defaults into the file
  1294. if not factory_defaults:
  1295. self.save_factory_defaults(silent=False)
  1296. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  1297. self.on_layout(index=None, lay='compact')
  1298. factory_file.close()
  1299. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  1300. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  1301. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  1302. # Post-GUI initialization: Experimental attempt
  1303. # to perform unit tests on the GUI.
  1304. # if post_gui is not None:
  1305. # post_gui(self)
  1306. App.log.debug("END of constructor. Releasing control.")
  1307. # accept a project file as command line parameter
  1308. # the path/file_name must be enclosed in quotes if it contain spaces
  1309. for argument in App.args:
  1310. if '.FlatPrj' in argument:
  1311. try:
  1312. project_name = str(argument)
  1313. if project_name == "":
  1314. self.inform.emit("Open cancelled.")
  1315. else:
  1316. # self.open_project(project_name)
  1317. run_from_arg = True
  1318. self.worker_task.emit({'fcn': self.open_project,
  1319. 'params': [project_name, run_from_arg]})
  1320. except Exception as e:
  1321. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1322. def defaults_read_form(self):
  1323. for option in self.defaults_form_fields:
  1324. try:
  1325. self.defaults[option] = self.defaults_form_fields[option].get_value()
  1326. except:
  1327. pass
  1328. def defaults_write_form(self):
  1329. for option in self.defaults:
  1330. self.defaults_write_form_field(option)
  1331. # try:
  1332. # self.defaults_form_fields[option].set_value(self.defaults[option])
  1333. # except KeyError:
  1334. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1335. # # TODO: Rethink this?
  1336. # pass
  1337. def defaults_write_form_field(self, field):
  1338. try:
  1339. self.defaults_form_fields[field].set_value(self.defaults[field])
  1340. except KeyError:
  1341. #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1342. # TODO: Rethink this?
  1343. pass
  1344. def clear_pool(self):
  1345. self.pool.close()
  1346. self.pool = Pool()
  1347. self.pool_recreated.emit(self.pool)
  1348. gc.collect()
  1349. # the order that the tools are installed is important as they can depend on each other install position
  1350. def install_tools(self):
  1351. self.dblsidedtool = DblSidedTool(self)
  1352. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  1353. self.measurement_tool = Measurement(self)
  1354. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  1355. self.panelize_tool = Panelize(self)
  1356. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  1357. self.film_tool = Film(self)
  1358. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  1359. self.paste_tool = SolderPaste(self)
  1360. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'), separator=True)
  1361. self.move_tool = ToolMove(self)
  1362. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  1363. before=self.ui.menueditorigin)
  1364. self.cutout_tool = CutOut(self)
  1365. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16.png'), pos=self.ui.menutool,
  1366. before=self.measurement_tool.menuAction)
  1367. self.ncclear_tool = NonCopperClear(self)
  1368. self.ncclear_tool.install(icon=QtGui.QIcon('share/flatcam_icon16.png'), pos=self.ui.menutool,
  1369. before=self.measurement_tool.menuAction, separator=True)
  1370. self.paint_tool = ToolPaint(self)
  1371. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  1372. before=self.measurement_tool.menuAction, separator=True)
  1373. self.calculator_tool = ToolCalculator(self)
  1374. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'))
  1375. self.transform_tool = ToolTransform(self)
  1376. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  1377. self.properties_tool = Properties(self)
  1378. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  1379. self.image_tool = ToolImage(self)
  1380. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  1381. separator=True)
  1382. self.log.debug("Tools are installed.")
  1383. def remove_tools(self):
  1384. for act in self.ui.menutool.actions():
  1385. self.ui.menutool.removeAction(act)
  1386. def init_tools(self):
  1387. log.debug("init_tools()")
  1388. # delete the data currently in the Tools Tab and the Tab itself
  1389. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1390. if widget is not None:
  1391. widget.deleteLater()
  1392. self.ui.notebook.removeTab(2)
  1393. # rebuild the Tools Tab
  1394. self.ui.tool_tab = QtWidgets.QWidget()
  1395. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1396. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1397. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1398. self.ui.tool_scroll_area = VerticalScrollArea()
  1399. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1400. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1401. # first remove all of them
  1402. self.remove_tools()
  1403. # second re add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1404. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  1405. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1406. # third install all of them
  1407. self.install_tools()
  1408. self.log.debug("Tools are initialized.")
  1409. # def parse_system_fonts(self):
  1410. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1411. # 'params': []})
  1412. def object2editor(self):
  1413. """
  1414. Send the current Geometry or Excellon object (if any) into the editor.
  1415. :return: None
  1416. """
  1417. self.report_usage("object2editor()")
  1418. # adjust the visibility of some of the canvas context menu
  1419. self.ui.popmenu_edit.setVisible(False)
  1420. self.ui.popmenu_save.setVisible(True)
  1421. edited_object = self.collection.get_active()
  1422. if isinstance(edited_object, FlatCAMGeometry):
  1423. # for now, if the Geometry is MultiGeo do not allow the editing
  1424. if edited_object.multigeo is True:
  1425. self.inform.emit("[WARNING_NOTCL]Editing a MultiGeo Geometry is not possible for the moment.")
  1426. return
  1427. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1428. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1429. self.geo_editor.edit_fcgeometry(edited_object)
  1430. # we set the notebook to hidden
  1431. self.ui.splitter.setSizes([0, 1])
  1432. # set call source to the Editor we go into
  1433. self.call_source = 'geo_editor'
  1434. elif isinstance(edited_object, FlatCAMExcellon):
  1435. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1436. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1437. self.exc_editor.edit_fcexcellon(edited_object)
  1438. # set call source to the Editor we go into
  1439. self.call_source = 'exc_editor'
  1440. else:
  1441. self.inform.emit("[WARNING_NOTCL]Select a Geometry or Excellon Object to edit.")
  1442. return
  1443. # make sure that we can't select another object while in Editor Mode:
  1444. self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1445. # delete any selection shape that might be active as they are not relevant in Editor
  1446. self.delete_selection_shape()
  1447. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1448. self.ui.plot_tab_area.protectTab(0)
  1449. self.inform.emit("[WARNING_NOTCL]Editor is activated ...")
  1450. self.should_we_save = True
  1451. def editor2object(self):
  1452. """
  1453. Transfers the Geometry or Excellon from the editor to the current object.
  1454. :return: None
  1455. """
  1456. self.report_usage("editor2object()")
  1457. # adjust the visibility of some of the canvas context menu
  1458. self.ui.popmenu_edit.setVisible(True)
  1459. self.ui.popmenu_save.setVisible(False)
  1460. edited_obj = self.collection.get_active()
  1461. obj_type = ""
  1462. if isinstance(edited_obj, FlatCAMGeometry):
  1463. obj_type = "Geometry"
  1464. self.geo_editor.update_fcgeometry(edited_obj)
  1465. self.geo_editor.update_options(edited_obj)
  1466. self.geo_editor.deactivate()
  1467. # update the geo object options so it is including the bounding box values
  1468. try:
  1469. xmin, ymin, xmax, ymax = edited_obj.bounds()
  1470. edited_obj.options['xmin'] = xmin
  1471. edited_obj.options['ymin'] = ymin
  1472. edited_obj.options['xmax'] = xmax
  1473. edited_obj.options['ymax'] = ymax
  1474. except AttributeError:
  1475. self.inform.emit("[WARNING] Object empty after edit.")
  1476. elif isinstance(edited_obj, FlatCAMExcellon):
  1477. obj_type = "Excellon"
  1478. self.exc_editor.update_fcexcellon(edited_obj)
  1479. self.exc_editor.update_options(edited_obj)
  1480. self.exc_editor.deactivate()
  1481. else:
  1482. self.inform.emit("[WARNING_NOTCL]Select a Geometry or Excellon Object to update.")
  1483. return
  1484. # if notebook is hidden we show it
  1485. if self.ui.splitter.sizes()[0] == 0:
  1486. self.ui.splitter.setSizes([1, 1])
  1487. # restore the call_source to app
  1488. self.call_source = 'app'
  1489. edited_obj.plot()
  1490. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1491. self.ui.plot_tab_area.protectTab(0)
  1492. self.inform.emit("[selected] %s is updated, returning to App..." % obj_type)
  1493. # reset the Object UI to original settings
  1494. # edited_obj.set_ui(edited_obj.ui_type())
  1495. # edited_obj.build_ui()
  1496. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1497. self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1498. def get_last_folder(self):
  1499. return self.defaults["global_last_folder"]
  1500. def get_last_save_folder(self):
  1501. loc = self.defaults["global_last_save_folder"]
  1502. if loc is None:
  1503. loc = self.defaults["global_last_folder"]
  1504. if loc is None:
  1505. loc = os.path.dirname(__file__)
  1506. return loc
  1507. def report_usage(self, resource):
  1508. """
  1509. Increments usage counter for the given resource
  1510. in self.defaults['global_stats'].
  1511. :param resource: Name of the resource.
  1512. :return: None
  1513. """
  1514. if resource in self.defaults['global_stats']:
  1515. self.defaults['global_stats'][resource] += 1
  1516. else:
  1517. self.defaults['global_stats'][resource] = 1
  1518. def init_tcl(self):
  1519. if hasattr(self,'tcl'):
  1520. # self.tcl = None
  1521. # TODO we need to clean non default variables and procedures here
  1522. # new object cannot be used here as it will not remember values created for next passes,
  1523. # because tcl was execudted in old instance of TCL
  1524. pass
  1525. else:
  1526. self.tcl = tk.Tcl()
  1527. self.setup_shell()
  1528. self.log.debug("TCL Shell has been initialized.")
  1529. # TODO: This shouldn't be here.
  1530. class TclErrorException(Exception):
  1531. """
  1532. this exception is deffined here, to be able catch it if we sucessfully handle all errors from shell command
  1533. """
  1534. pass
  1535. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  1536. """
  1537. Shows a message on the FlatCAM Shell
  1538. :param msg: Message to display.
  1539. :param show: Opens the shell.
  1540. :param error: Shows the message as an error.
  1541. :return: None
  1542. """
  1543. if show:
  1544. self.ui.shell_dock.show()
  1545. try:
  1546. if error:
  1547. self.shell.append_error(msg + "\n")
  1548. elif warning:
  1549. self.shell.append_warning(msg + "\n")
  1550. elif success:
  1551. self.shell.append_success(msg + "\n")
  1552. elif selected:
  1553. self.shell.append_selected(msg + "\n")
  1554. else:
  1555. self.shell.append_output(msg + "\n")
  1556. except AttributeError:
  1557. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  1558. def raise_tcl_unknown_error(self, unknownException):
  1559. """
  1560. Raise exception if is different type than TclErrorException
  1561. this is here mainly to show unknown errors inside TCL shell console.
  1562. :param unknownException:
  1563. :return:
  1564. """
  1565. if not isinstance(unknownException, self.TclErrorException):
  1566. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  1567. else:
  1568. raise unknownException
  1569. def display_tcl_error(self, error, error_info=None):
  1570. """
  1571. escape bracket [ with \ otherwise there is error
  1572. "ERROR: missing close-bracket" instead of real error
  1573. :param error: it may be text or exception
  1574. :return: None
  1575. """
  1576. if isinstance(error, Exception):
  1577. exc_type, exc_value, exc_traceback = error_info
  1578. if not isinstance(error, self.TclErrorException):
  1579. show_trace = 1
  1580. else:
  1581. show_trace = int(self.defaults['global_verbose_error_level'])
  1582. if show_trace > 0:
  1583. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  1584. trc_formated = []
  1585. for a in reversed(trc):
  1586. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  1587. text = "%s\nPython traceback: %s\n%s" % (exc_value,
  1588. exc_type,
  1589. "\n".join(trc_formated))
  1590. else:
  1591. text = "%s" % error
  1592. else:
  1593. text = error
  1594. text = text.replace('[', '\\[').replace('"', '\\"')
  1595. self.tcl.eval('return -code error "%s"' % text)
  1596. def raise_tcl_error(self, text):
  1597. """
  1598. this method pass exception from python into TCL as error, so we get stacktrace and reason
  1599. :param text: text of error
  1600. :return: raise exception
  1601. """
  1602. self.display_tcl_error(text)
  1603. raise self.TclErrorException(text)
  1604. def exec_command(self, text):
  1605. """
  1606. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  1607. Also handles execution in separated threads
  1608. :param text:
  1609. :return: output if there was any
  1610. """
  1611. self.report_usage('exec_command')
  1612. result = self.exec_command_test(text, False)
  1613. #MS: added this method call so the geometry is updated once the TCL
  1614. #command is executed
  1615. self.plot_all()
  1616. return result
  1617. def exec_command_test(self, text, reraise=True):
  1618. """
  1619. Same as exec_command(...) with additional control over exceptions.
  1620. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  1621. :param text: Input command
  1622. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  1623. :return: Output from the command
  1624. """
  1625. text = str(text)
  1626. try:
  1627. self.shell.open_proccessing() # Disables input box.
  1628. result = self.tcl.eval(str(text))
  1629. if result != 'None':
  1630. self.shell.append_output(result + '\n')
  1631. except tk.TclError as e:
  1632. # This will display more precise answer if something in TCL shell fails
  1633. result = self.tcl.eval("set errorInfo")
  1634. self.log.error("Exec command Exception: %s" % (result + '\n'))
  1635. self.shell.append_error('ERROR: ' + result + '\n')
  1636. # Show error in console and just return or in test raise exception
  1637. if reraise:
  1638. raise e
  1639. finally:
  1640. self.shell.close_proccessing()
  1641. pass
  1642. return result
  1643. # """
  1644. # Code below is unsused. Saved for later.
  1645. # """
  1646. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  1647. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  1648. # self.log.debug(parts)
  1649. # try:
  1650. # if parts[0] not in commands:
  1651. # self.shell.append_error("Unknown command\n")
  1652. # return
  1653. #
  1654. # #import inspect
  1655. # #inspect.getargspec(someMethod)
  1656. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  1657. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  1658. # self.shell.append_error(
  1659. # "Command %s takes %d arguments. %d given.\n" %
  1660. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  1661. # )
  1662. # return
  1663. #
  1664. # cmdfcn = commands[parts[0]]["fcn"]
  1665. # cmdconv = commands[parts[0]]["converters"]
  1666. # if len(parts) - 1 > 0:
  1667. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  1668. # else:
  1669. # retval = cmdfcn()
  1670. # retfcn = commands[parts[0]]["retfcn"]
  1671. # if retval and retfcn(retval):
  1672. # self.shell.append_output(retfcn(retval) + "\n")
  1673. #
  1674. # except Exception as e:
  1675. # #self.shell.append_error(''.join(traceback.format_exc()))
  1676. # #self.shell.append_error("?\n")
  1677. # self.shell.append_error(str(e) + "\n")
  1678. def info(self, msg):
  1679. """
  1680. Informs the user. Normally on the status bar, optionally
  1681. also on the shell.
  1682. :param msg: Text to write.
  1683. :return: None
  1684. """
  1685. # Type of message in brackets at the begining of the message.
  1686. match = re.search("\[([^\]]+)\](.*)", msg)
  1687. if match:
  1688. level = match.group(1)
  1689. msg_ = match.group(2)
  1690. self.ui.fcinfo.set_status(str(msg_), level=level)
  1691. if level.lower() == "error":
  1692. self.shell_message(msg, error=True, show=True)
  1693. elif level.lower() == "warning":
  1694. self.shell_message(msg, warning=True, show=True)
  1695. elif level.lower() == "error_notcl":
  1696. self.shell_message(msg, error=True, show=False)
  1697. elif level.lower() == "warning_notcl":
  1698. self.shell_message(msg, warning=True, show=False)
  1699. elif level.lower() == "success":
  1700. self.shell_message(msg, success=True, show=False)
  1701. elif level.lower() == "selected":
  1702. self.shell_message(msg, selected=True, show=False)
  1703. else:
  1704. self.shell_message(msg, show=False)
  1705. else:
  1706. self.ui.fcinfo.set_status(str(msg), level="info")
  1707. # make sure that if the message is to clear the infobar with a space
  1708. # is not printed over and over on the shell
  1709. if msg != '':
  1710. self.shell_message(msg)
  1711. def restore_toolbar_view(self):
  1712. tb = self.defaults["global_toolbar_view"]
  1713. if tb & 1:
  1714. self.ui.toolbarfile.setVisible(True)
  1715. else:
  1716. self.ui.toolbarfile.setVisible(False)
  1717. if tb & 2:
  1718. self.ui.toolbargeo.setVisible(True)
  1719. else:
  1720. self.ui.toolbargeo.setVisible(False)
  1721. if tb & 4:
  1722. self.ui.toolbarview.setVisible(True)
  1723. else:
  1724. self.ui.toolbarview.setVisible(False)
  1725. if tb & 8:
  1726. self.ui.toolbartools.setVisible(True)
  1727. else:
  1728. self.ui.toolbartools.setVisible(False)
  1729. if tb & 16:
  1730. self.ui.exc_edit_toolbar.setVisible(True)
  1731. else:
  1732. self.ui.exc_edit_toolbar.setVisible(False)
  1733. if tb & 32:
  1734. self.ui.geo_edit_toolbar.setVisible(True)
  1735. else:
  1736. self.ui.geo_edit_toolbar.setVisible(False)
  1737. if tb & 64:
  1738. self.ui.snap_toolbar.setVisible(True)
  1739. else:
  1740. self.ui.snap_toolbar.setVisible(False)
  1741. def load_defaults(self, filename):
  1742. """
  1743. Loads the aplication's default settings from current_defaults.FlatConfig into
  1744. ``self.defaults``.
  1745. :return: None
  1746. """
  1747. try:
  1748. f = open(self.data_path + "/" + filename + ".FlatConfig")
  1749. options = f.read()
  1750. f.close()
  1751. except IOError:
  1752. self.log.error("Could not load defaults file.")
  1753. self.inform.emit("[ERROR] Could not load defaults file.")
  1754. # in case the defaults file can't be loaded, show all toolbars
  1755. self.defaults["global_toolbar_view"] = 127
  1756. return
  1757. try:
  1758. defaults = json.loads(options)
  1759. except:
  1760. # in case the defaults file can't be loaded, show all toolbars
  1761. self.defaults["global_toolbar_view"] = 127
  1762. e = sys.exc_info()[0]
  1763. App.log.error(str(e))
  1764. self.inform.emit("[ERROR] Failed to parse defaults file.")
  1765. return
  1766. self.defaults.update(defaults)
  1767. log.debug("FlatCAM defaults loaded from: %s" % filename)
  1768. # restore the toolbar view
  1769. self.restore_toolbar_view()
  1770. def on_import_preferences(self):
  1771. """
  1772. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  1773. ``self.defaults``.
  1774. :return: None
  1775. """
  1776. self.report_usage("on_import_preferences")
  1777. App.log.debug("on_import_preferences()")
  1778. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  1779. try:
  1780. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Import FlatCAM Preferences",
  1781. directory=self.data_path, filter=filter)
  1782. except TypeError:
  1783. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Import FlatCAM Preferences", filter=filter)
  1784. filename = str(filename)
  1785. if filename == "":
  1786. self.inform.emit("[WARNING_NOTCL]FlatCAM preferences import cancelled.")
  1787. else:
  1788. try:
  1789. f = open(filename)
  1790. options = f.read()
  1791. f.close()
  1792. except IOError:
  1793. self.log.error("Could not load defaults file.")
  1794. self.inform.emit("[ERROR_NOTCL] Could not load defaults file.")
  1795. return
  1796. try:
  1797. defaults_from_file = json.loads(options)
  1798. except:
  1799. e = sys.exc_info()[0]
  1800. App.log.error(str(e))
  1801. self.inform.emit("[ERROR_NOTCL] Failed to parse defaults file.")
  1802. return
  1803. self.defaults.update(defaults_from_file)
  1804. self.inform.emit("[success]Imported Defaults from %s" %filename)
  1805. def on_export_preferences(self):
  1806. self.report_usage("on_export_preferences")
  1807. App.log.debug("on_export_preferences()")
  1808. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  1809. try:
  1810. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  1811. caption="Export FlatCAM Preferences",
  1812. directory=self.data_path + '/preferences_' + self.date.replace('-', ''), filter=filter
  1813. )
  1814. except TypeError:
  1815. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export FlatCAM Preferences", filter=filter)
  1816. filename = str(filename)
  1817. defaults_from_file = {}
  1818. if filename == "":
  1819. self.inform.emit("[WARNING_NOTCL]FlatCAM preferences export cancelled.")
  1820. return
  1821. else:
  1822. try:
  1823. f = open(filename, 'w')
  1824. defaults_file_content = f.read()
  1825. f.close()
  1826. except IOError:
  1827. App.log.debug('Creating a new preferences file ...')
  1828. f = open(filename, 'w')
  1829. json.dump({}, f)
  1830. f.close()
  1831. except:
  1832. e = sys.exc_info()[0]
  1833. App.log.error("Could not load defaults file.")
  1834. App.log.error(str(e))
  1835. self.inform.emit("[ERROR_NOTCL]Could not load defaults file.")
  1836. return
  1837. try:
  1838. defaults_from_file = json.loads(defaults_file_content)
  1839. except:
  1840. App.log.warning("Trying to read an empty Preferences file. Continue.")
  1841. # Update options
  1842. self.defaults_read_form()
  1843. defaults_from_file.update(self.defaults)
  1844. self.propagate_defaults(silent=True)
  1845. # Save update options
  1846. try:
  1847. f = open(filename, "w")
  1848. json.dump(defaults_from_file, f)
  1849. f.close()
  1850. except:
  1851. self.inform.emit("[ERROR_NOTCL] Failed to write defaults to file.")
  1852. return
  1853. self.file_saved.emit("preferences", filename)
  1854. self.inform.emit("[success]Exported Defaults to %s" % filename)
  1855. def on_preferences_open_folder(self):
  1856. self.report_usage("on_preferences_open_folder()")
  1857. if sys.platform == 'win32':
  1858. subprocess.Popen('explorer %s' % self.data_path)
  1859. elif sys.platform == 'darwin':
  1860. os.system('open "%s"' % self.data_path)
  1861. else:
  1862. subprocess.Popen(['xdg-open', self.data_path])
  1863. self.inform.emit("[success]FlatCAM Preferences Folder opened.")
  1864. def save_geometry(self, x, y, width, height, notebook_width):
  1865. self.defaults["global_def_win_x"] = x
  1866. self.defaults["global_def_win_y"] = y
  1867. self.defaults["global_def_win_w"] = width
  1868. self.defaults["global_def_win_h"] = height
  1869. self.defaults["def_notebook_width"] = notebook_width
  1870. self.save_defaults()
  1871. def message_dialog(self, title, message, kind="info"):
  1872. icon = {"info": QtWidgets.QMessageBox.Information,
  1873. "warning": QtWidgets.QMessageBox.Warning,
  1874. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  1875. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  1876. dlg.setText(message)
  1877. dlg.exec_()
  1878. def register_recent(self, kind, filename):
  1879. self.log.debug("register_recent()")
  1880. self.log.debug(" %s" % kind)
  1881. self.log.debug(" %s" % filename)
  1882. record = {'kind': str(kind), 'filename': str(filename)}
  1883. if record in self.recent:
  1884. return
  1885. self.recent.insert(0, record)
  1886. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  1887. self.recent.pop()
  1888. try:
  1889. f = open(self.data_path + '/recent.json', 'w')
  1890. except IOError:
  1891. App.log.error("Failed to open recent items file for writing.")
  1892. self.inform.emit('[ERROR_NOTCL]Failed to open recent files file for writing.')
  1893. return
  1894. #try:
  1895. json.dump(self.recent, f)
  1896. # except:
  1897. # App.log.error("Failed to write to recent items file.")
  1898. # self.inform.emit('ERROR: Failed to write to recent items file.')
  1899. # f.close()
  1900. f.close()
  1901. # Re-buid the recent items menu
  1902. self.setup_recent_items()
  1903. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  1904. """
  1905. Creates a new specalized FlatCAMObj and attaches it to the application,
  1906. this is, updates the GUI accordingly, any other records and plots it.
  1907. This method is thread-safe.
  1908. Notes:
  1909. * If the name is in use, the self.collection will modify it
  1910. when appending it to the collection. There is no need to handle
  1911. name conflicts here.
  1912. :param kind: The kind of object to create. One of 'gerber',
  1913. 'excellon', 'cncjob' and 'geometry'.
  1914. :type kind: str
  1915. :param name: Name for the object.
  1916. :type name: str
  1917. :param initialize: Function to run after creation of the object
  1918. but before it is attached to the application. The function is
  1919. called with 2 parameters: the new object and the App instance.
  1920. :type initialize: function
  1921. :return: None
  1922. :rtype: None
  1923. """
  1924. App.log.debug("new_object()")
  1925. self.plot = plot
  1926. self.autoselected = autoselected
  1927. t0 = time.time() # Debug
  1928. ## Create object
  1929. classdict = {
  1930. "gerber": FlatCAMGerber,
  1931. "excellon": FlatCAMExcellon,
  1932. "cncjob": FlatCAMCNCjob,
  1933. "geometry": FlatCAMGeometry
  1934. }
  1935. App.log.debug("Calling object constructor...")
  1936. obj = classdict[kind](name)
  1937. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  1938. # Set options from "Project options" form
  1939. self.options_read_form()
  1940. # IMPORTANT
  1941. # The key names in defaults and options dictionary's are not random:
  1942. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  1943. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  1944. # the options from project options form into the self.options. After that, below, depending on the type of
  1945. # object that is created, it will strip the name of the object and the underline (if the original key was
  1946. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  1947. # "toolchange"
  1948. for option in self.options:
  1949. if option.find(kind + "_") == 0:
  1950. oname = option[len(kind) + 1:]
  1951. obj.options[oname] = self.options[option]
  1952. # if kind == 'geometry':
  1953. # obj.tools = {}
  1954. # elif kind == 'cncjob':
  1955. # obj.cnc_tools = {}
  1956. # Initialize as per user request
  1957. # User must take care to implement initialize
  1958. # in a thread-safe way as is is likely that we
  1959. # have been invoked in a separate thread.
  1960. t1 = time.time()
  1961. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  1962. try:
  1963. return_value = initialize(obj, self)
  1964. except Exception as e:
  1965. msg = "[ERROR_NOTCL] An internal error has ocurred. See shell.\n"
  1966. msg += "Object (%s) failed because: %s \n\n" % (kind, str(e))
  1967. msg += traceback.format_exc()
  1968. self.inform.emit(msg)
  1969. # if str(e) == "Empty Geometry":
  1970. # self.inform.emit("[ERROR_NOTCL] )
  1971. # else:
  1972. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  1973. return "fail"
  1974. t2 = time.time()
  1975. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  1976. if return_value == 'fail':
  1977. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  1978. return "fail"
  1979. # Check units and convert if necessary
  1980. # This condition CAN be true because initialize() can change obj.units
  1981. if self.options["units"].upper() != obj.units.upper():
  1982. self.inform.emit("Converting units to " + self.options["units"] + ".")
  1983. obj.convert_units(self.options["units"])
  1984. t3 = time.time()
  1985. self.log.debug("%f seconds converting units." % (t3 - t2))
  1986. # Create the bounding box for the object and then add the results to the obj.options
  1987. try:
  1988. xmin, ymin, xmax, ymax = obj.bounds()
  1989. obj.options['xmin'] = xmin
  1990. obj.options['ymin'] = ymin
  1991. obj.options['xmax'] = xmax
  1992. obj.options['ymax'] = ymax
  1993. except:
  1994. log.warning("The object has no bounds properties.")
  1995. # don't plot objects with no bounds, there is nothing to plot
  1996. self.plot = False
  1997. pass
  1998. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  1999. # Move the object to the main thread and let the app know that it is available.
  2000. obj.moveToThread(QtWidgets.QApplication.instance().thread())
  2001. self.object_created.emit(obj, self.plot, self.autoselected)
  2002. return obj
  2003. def new_excellon_object(self):
  2004. self.report_usage("new_excellon_object()")
  2005. self.new_object('excellon', 'new_e', lambda x, y: None, plot=False)
  2006. def new_geometry_object(self):
  2007. self.report_usage("new_geometry_object()")
  2008. def initialize(obj, self):
  2009. obj.multitool = False
  2010. self.new_object('geometry', 'new_g', initialize, plot=False)
  2011. def on_object_created(self, obj, plot, autoselect):
  2012. """
  2013. Event callback for object creation.
  2014. :param obj: The newly created FlatCAM object.
  2015. :return: None
  2016. """
  2017. t0 = time.time() # DEBUG
  2018. self.log.debug("on_object_created()")
  2019. # The Collection might change the name if there is a collision
  2020. self.collection.append(obj)
  2021. # after adding the object to the collection always update the list of objects that are in the collection
  2022. self.all_objects_list = self.collection.get_list()
  2023. # self.inform.emit('[selected] %s created & selected: %s' %
  2024. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  2025. if obj.kind == 'gerber':
  2026. self.inform.emit('[selected]%s created/selected: <span style="color:%s;">%s</span>' %
  2027. (obj.kind.capitalize(), 'green', str(obj.options['name'])))
  2028. elif obj.kind == 'excellon':
  2029. self.inform.emit('[selected]%s created/selected: <span style="color:%s;">%s</span>' %
  2030. (obj.kind.capitalize(), 'brown', str(obj.options['name'])))
  2031. elif obj.kind == 'cncjob':
  2032. self.inform.emit('[selected]%s created/selected: <span style="color:%s;">%s</span>' %
  2033. (obj.kind.capitalize(), 'blue', str(obj.options['name'])))
  2034. elif obj.kind == 'geometry':
  2035. self.inform.emit('[selected]%s created/selected: <span style="color:%s;">%s</span>' %
  2036. (obj.kind.capitalize(), 'red', str(obj.options['name'])))
  2037. # self.new_object_available.emit(obj)
  2038. # update the SHELL auto-completer model with the name of the new object
  2039. self.myKeywords.append(obj.options['name'])
  2040. self.shell._edit.set_model_data(self.myKeywords)
  2041. if autoselect:
  2042. # select the just opened object but deselect the previous ones
  2043. self.collection.set_all_inactive()
  2044. self.collection.set_active(obj.options["name"])
  2045. # here it is done the object plotting
  2046. def worker_task(obj):
  2047. with self.proc_container.new("Plotting"):
  2048. if isinstance(obj, FlatCAMCNCjob):
  2049. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  2050. else:
  2051. obj.plot()
  2052. t1 = time.time() # DEBUG
  2053. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  2054. self.object_plotted.emit(obj)
  2055. # Send to worker
  2056. # self.worker.add_task(worker_task, [self])
  2057. if plot is True:
  2058. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  2059. def on_object_changed(self, obj):
  2060. # update the bounding box data from obj.options
  2061. xmin, ymin, xmax, ymax = obj.bounds()
  2062. obj.options['xmin'] = xmin
  2063. obj.options['ymin'] = ymin
  2064. obj.options['xmax'] = xmax
  2065. obj.options['ymax'] = ymax
  2066. log.debug("Object changed, updating the bounding box data on self.options")
  2067. # delete the old selection shape
  2068. self.delete_selection_shape()
  2069. self.should_we_save = True
  2070. def on_object_plotted(self, obj):
  2071. self.on_zoom_fit(None)
  2072. def options_read_form(self):
  2073. for option in self.options_form_fields:
  2074. self.options[option] = self.options_form_fields[option].get_value()
  2075. def options_write_form(self):
  2076. for option in self.options:
  2077. self.options_write_form_field(option)
  2078. def options_write_form_field(self, field):
  2079. try:
  2080. self.options_form_fields[field].set_value(self.options[field])
  2081. except KeyError:
  2082. # Changed from error to debug. This allows to have data stored
  2083. # which is not user-editable.
  2084. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  2085. pass
  2086. def on_about(self):
  2087. """
  2088. Displays the "about" dialog.
  2089. :return: None
  2090. """
  2091. self.report_usage("on_about")
  2092. version = self.version
  2093. version_date = self.version_date
  2094. beta = self.beta
  2095. class AboutDialog(QtWidgets.QDialog):
  2096. def __init__(self, parent=None):
  2097. QtWidgets.QDialog.__init__(self, parent)
  2098. # Icon and title
  2099. self.setWindowIcon(parent.app_icon)
  2100. self.setWindowTitle("FlatCAM")
  2101. layout1 = QtWidgets.QVBoxLayout()
  2102. self.setLayout(layout1)
  2103. layout2 = QtWidgets.QHBoxLayout()
  2104. layout1.addLayout(layout2)
  2105. logo = QtWidgets.QLabel()
  2106. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  2107. layout2.addWidget(logo, stretch=0)
  2108. title = QtWidgets.QLabel(
  2109. "<font size=8><B>FlatCAM</B></font><BR>"
  2110. "Version %s %s (%s) - %s <BR>"
  2111. "<BR>"
  2112. "2D Computer-Aided Printed Circuit Board<BR>"
  2113. "Manufacturing.<BR>"
  2114. "<BR>"
  2115. "(c) 2014-2019 <B>Juan Pablo Caram</B><BR>"
  2116. "<BR>"
  2117. "<B> Main Contributors:</B><BR>"
  2118. "Denis Hayrullin<BR>"
  2119. "Kamil Sopko<BR>"
  2120. "Marius Stanciu<BR>"
  2121. "Matthieu Berthomé<BR>"
  2122. "and many others found "
  2123. "<a href = \"https://bitbucket.org/jpcgt/flatcam/pull-requests/?state=MERGED\">here.</a><BR>"
  2124. "<BR>"
  2125. "Development is done "
  2126. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\">here.</a><BR>"
  2127. "DOWNLOAD area "
  2128. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\">here.</a><BR>"
  2129. "" % (version, ('BETA' if beta else ''), version_date, platform.architecture()[0])
  2130. )
  2131. title.setOpenExternalLinks(True)
  2132. layout2.addWidget(title, stretch=1)
  2133. layout3 = QtWidgets.QHBoxLayout()
  2134. layout1.addLayout(layout3)
  2135. layout3.addStretch()
  2136. okbtn = QtWidgets.QPushButton("Close")
  2137. layout3.addWidget(okbtn)
  2138. okbtn.clicked.connect(self.accept)
  2139. AboutDialog(self.ui).exec_()
  2140. def on_file_savedefaults(self):
  2141. """
  2142. Callback for menu item File->Save Defaults. Saves application default options
  2143. ``self.defaults`` to current_defaults.FlatConfig.
  2144. :return: None
  2145. """
  2146. self.save_defaults()
  2147. def on_app_exit(self):
  2148. self.report_usage("on_app_exit()")
  2149. if self.collection.get_list():
  2150. msgbox = QtWidgets.QMessageBox()
  2151. # msgbox.setText("<B>Save changes ...</B>")
  2152. msgbox.setText("There are files/objects opened in FlatCAM. "
  2153. "\n"
  2154. "Do you want to Save the project?")
  2155. msgbox.setWindowTitle("Save changes")
  2156. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2157. msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  2158. QtWidgets.QMessageBox.Cancel)
  2159. msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  2160. response = msgbox.exec_()
  2161. if response == QtWidgets.QMessageBox.Yes:
  2162. self.on_file_saveprojectas(thread=False)
  2163. elif response == QtWidgets.QMessageBox.Cancel:
  2164. return
  2165. self.save_defaults()
  2166. else:
  2167. self.save_defaults()
  2168. log.debug("Application defaults saved ... Exit event.")
  2169. QtWidgets.qApp.quit()
  2170. def save_defaults(self, silent=False):
  2171. """
  2172. Saves application default options
  2173. ``self.defaults`` to current_defaults.FlatConfig.
  2174. :return: None
  2175. """
  2176. self.report_usage("save_defaults")
  2177. # Read options from file
  2178. try:
  2179. f = open(self.data_path + "/current_defaults.FlatConfig")
  2180. defaults_file_content = f.read()
  2181. f.close()
  2182. except:
  2183. e = sys.exc_info()[0]
  2184. App.log.error("Could not load defaults file.")
  2185. App.log.error(str(e))
  2186. self.inform.emit("[ERROR_NOTCL] Could not load defaults file.")
  2187. return
  2188. try:
  2189. defaults = json.loads(defaults_file_content)
  2190. except:
  2191. e = sys.exc_info()[0]
  2192. App.log.error("Failed to parse defaults file.")
  2193. App.log.error(str(e))
  2194. self.inform.emit("[ERROR_NOTCL] Failed to parse defaults file.")
  2195. return
  2196. # Update options
  2197. self.defaults_read_form()
  2198. defaults.update(self.defaults)
  2199. self.propagate_defaults(silent=True)
  2200. # Save update options
  2201. try:
  2202. f = open(self.data_path + "/current_defaults.FlatConfig", "w")
  2203. json.dump(defaults, f)
  2204. f.close()
  2205. except:
  2206. self.inform.emit("[ERROR_NOTCL] Failed to write defaults to file.")
  2207. return
  2208. # Save the toolbar view
  2209. tb_status = 0
  2210. if self.ui.toolbarfile.isVisible():
  2211. tb_status += 1
  2212. if self.ui.toolbargeo.isVisible():
  2213. tb_status += 2
  2214. if self.ui.toolbarview.isVisible():
  2215. tb_status += 4
  2216. if self.ui.toolbartools.isVisible():
  2217. tb_status += 8
  2218. if self.ui.exc_edit_toolbar.isVisible():
  2219. tb_status += 16
  2220. if self.ui.geo_edit_toolbar.isVisible():
  2221. tb_status += 32
  2222. if self.ui.snap_toolbar.isVisible():
  2223. tb_status += 64
  2224. self.defaults["global_toolbar_view"] = tb_status
  2225. if not silent:
  2226. self.inform.emit("[success]Defaults saved.")
  2227. def save_factory_defaults(self, silent=False):
  2228. """
  2229. Saves application factory default options
  2230. ``self.defaults`` to factory_defaults.FlatConfig.
  2231. It's a one time job done just after the first install.
  2232. :return: None
  2233. """
  2234. self.report_usage("save_factory_defaults")
  2235. # Read options from file
  2236. try:
  2237. f_f_def = open(self.data_path + "/factory_defaults.FlatConfig")
  2238. factory_defaults_file_content = f_f_def.read()
  2239. f_f_def.close()
  2240. except:
  2241. e = sys.exc_info()[0]
  2242. App.log.error("Could not load factory defaults file.")
  2243. App.log.error(str(e))
  2244. self.inform.emit("[ERROR_NOTCL] Could not load factory defaults file.")
  2245. return
  2246. try:
  2247. factory_defaults = json.loads(factory_defaults_file_content)
  2248. except:
  2249. e = sys.exc_info()[0]
  2250. App.log.error("Failed to parse factory defaults file.")
  2251. App.log.error(str(e))
  2252. self.inform.emit("[ERROR_NOTCL] Failed to parse factory defaults file.")
  2253. return
  2254. # Update options
  2255. self.defaults_read_form()
  2256. factory_defaults.update(self.defaults)
  2257. self.propagate_defaults(silent=True)
  2258. # Save update options
  2259. try:
  2260. f_f_def_s = open(self.data_path + "/factory_defaults.FlatConfig", "w")
  2261. json.dump(factory_defaults, f_f_def_s)
  2262. f_f_def_s.close()
  2263. except:
  2264. self.inform.emit("[ERROR_NOTCL] Failed to write factory defaults to file.")
  2265. return
  2266. if silent is False:
  2267. self.inform.emit("Factory defaults saved.")
  2268. def final_save(self):
  2269. if self.should_we_save and self.collection.get_list():
  2270. msgbox = QtWidgets.QMessageBox()
  2271. # msgbox.setText("<B>Save changes ...</B>")
  2272. msgbox.setText("There are files/objects modified in FlatCAM. "
  2273. "\n"
  2274. "Do you want to Save the project?")
  2275. msgbox.setWindowTitle("Save changes")
  2276. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2277. msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  2278. QtWidgets.QMessageBox.Cancel)
  2279. msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  2280. response = msgbox.exec_()
  2281. if response == QtWidgets.QMessageBox.Yes:
  2282. self.on_file_saveprojectas(thread=False)
  2283. elif response == QtWidgets.QMessageBox.Cancel:
  2284. self.should_we_quit = False
  2285. return
  2286. self.save_defaults()
  2287. log.debug("Application defaults saved ... Exit event.")
  2288. def on_toggle_shell(self):
  2289. """
  2290. toggle shell if is visible close it if closed open it
  2291. :return:
  2292. """
  2293. self.report_usage("on_toggle_shell()")
  2294. if self.ui.shell_dock.isVisible():
  2295. self.ui.shell_dock.hide()
  2296. else:
  2297. self.ui.shell_dock.show()
  2298. def on_edit_join(self, name=None):
  2299. """
  2300. Callback for Edit->Join. Joins the selected geometry objects into
  2301. a new one.
  2302. :return: None
  2303. """
  2304. self.report_usage("on_edit_join()")
  2305. obj_name_single = str(name) if name else "Combo_SingleGeo"
  2306. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  2307. tooldias = []
  2308. geo_type_list = []
  2309. objs = self.collection.get_selected()
  2310. for obj in objs:
  2311. geo_type_list.append(obj.multigeo)
  2312. # if len(set(geo_type_list)) == 1 means that all list elements are the same
  2313. if len(set(geo_type_list)) != 1:
  2314. self.inform.emit("[ERROR] Failed join. The Geometry objects are of different types.\n"
  2315. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  2316. "convert from one to another and retry joining \n"
  2317. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  2318. "the result may not be what was expected. \n"
  2319. "Check the generated GCODE.")
  2320. return
  2321. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  2322. if True in geo_type_list:
  2323. def initialize(obj, app):
  2324. FlatCAMGeometry.merge(objs, obj, multigeo=True)
  2325. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2326. for v in obj.tools.values():
  2327. v['data']['name'] = obj_name_multi
  2328. self.new_object("geometry", obj_name_multi, initialize)
  2329. else:
  2330. def initialize(obj, app):
  2331. FlatCAMGeometry.merge(objs, obj, multigeo=False)
  2332. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2333. for v in obj.tools.values():
  2334. v['data']['name'] = obj_name_single
  2335. self.new_object("geometry", obj_name_single, initialize)
  2336. self.should_we_save = True
  2337. def on_edit_join_exc(self):
  2338. """
  2339. Callback for Edit->Join Excellon. Joins the selected excellon objects into
  2340. a new one.
  2341. :return: None
  2342. """
  2343. self.report_usage("on_edit_join_exc()")
  2344. objs = self.collection.get_selected()
  2345. for obj in objs:
  2346. if not isinstance(obj, FlatCAMExcellon):
  2347. self.inform.emit("[ERROR_NOTCL]Failed. Excellon joining works only on Excellon objects.")
  2348. return
  2349. def initialize(obj, app):
  2350. FlatCAMExcellon.merge(objs, obj)
  2351. self.new_object("excellon", 'Combo_Excellon', initialize)
  2352. self.should_we_save = True
  2353. def on_edit_join_grb(self):
  2354. """
  2355. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  2356. a new one.
  2357. :return: None
  2358. """
  2359. self.report_usage("on_edit_join_grb()")
  2360. objs = self.collection.get_selected()
  2361. for obj in objs:
  2362. if not isinstance(obj, FlatCAMGerber):
  2363. self.inform.emit("[ERROR_NOTCL]Failed. Gerber joining works only on Gerber objects.")
  2364. return
  2365. def initialize(obj, app):
  2366. FlatCAMGerber.merge(objs, obj)
  2367. self.new_object("gerber", 'Combo_Gerber', initialize)
  2368. self.should_we_save = True
  2369. def on_convert_singlegeo_to_multigeo(self):
  2370. self.report_usage("on_convert_singlegeo_to_multigeo()")
  2371. obj = self.collection.get_active()
  2372. if obj is None:
  2373. self.inform.emit("[ERROR_NOTCL]Failed. Select a Geometry Object and try again.")
  2374. return
  2375. if not isinstance(obj, FlatCAMGeometry):
  2376. self.inform.emit("[ERROR_NOTCL]Expected a FlatCAMGeometry, got %s" % type(obj))
  2377. return
  2378. obj.multigeo = True
  2379. for tooluid, dict_value in obj.tools.items():
  2380. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  2381. if not isinstance(obj.solid_geometry, list):
  2382. obj.solid_geometry = [obj.solid_geometry]
  2383. obj.solid_geometry[:] = []
  2384. obj.plot()
  2385. self.should_we_save = True
  2386. self.inform.emit("[success] A Geometry object was converted to MultiGeo type.")
  2387. def on_convert_multigeo_to_singlegeo(self):
  2388. self.report_usage("on_convert_multigeo_to_singlegeo()")
  2389. obj = self.collection.get_active()
  2390. if obj is None:
  2391. self.inform.emit("[ERROR_NOTCL]Failed. Select a Geometry Object and try again.")
  2392. return
  2393. if not isinstance(obj, FlatCAMGeometry):
  2394. self.inform.emit("[ERROR_NOTCL]Expected a FlatCAMGeometry, got %s" % type(obj))
  2395. return
  2396. obj.multigeo = False
  2397. total_solid_geometry = []
  2398. for tooluid, dict_value in obj.tools.items():
  2399. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  2400. # clear the original geometry
  2401. dict_value['solid_geometry'][:] = []
  2402. obj.solid_geometry = deepcopy(total_solid_geometry)
  2403. obj.plot()
  2404. self.should_we_save = True
  2405. self.inform.emit("[success] A Geometry object was converted to SingleGeo type.")
  2406. def on_options_dict_change(self, field):
  2407. self.options_write_form_field(field)
  2408. if field == "units":
  2409. self.set_screen_units(self.options['units'])
  2410. def on_defaults_dict_change(self, field):
  2411. self.defaults_write_form_field(field)
  2412. def set_screen_units(self, units):
  2413. self.ui.units_label.setText("[" + self.options["units"].lower() + "]")
  2414. def on_toggle_units(self):
  2415. """
  2416. Callback for the Units radio-button change in the Options tab.
  2417. Changes the application's default units or the current project's units.
  2418. If changing the project's units, the change propagates to all of
  2419. the objects in the project.
  2420. :return: None
  2421. """
  2422. self.report_usage("on_toggle_units")
  2423. if self.toggle_units_ignore:
  2424. return
  2425. # If option is the same, then ignore
  2426. if self.general_options_form.general_app_group.units_radio.get_value().upper() == self.options["units"].upper():
  2427. self.log.debug("on_toggle_units(): Same as options, so ignoring.")
  2428. return
  2429. # Options to scale
  2430. dimensions = ['gerber_isotooldia', 'tools_cutoutmargin', 'tools_cutoutgapsize',
  2431. 'gerber_noncoppermargin', 'gerber_bboxmargin','gerber_isooverlap','tools_nccoverlap',
  2432. 'tools_nccmargin','tools_cutouttooldia','tools_cutoutgapsize',
  2433. 'gerber_noncoppermargin','gerber_bboxmargin',
  2434. 'excellon_drillz', "excellon_toolchangexy",
  2435. 'excellon_travelz', 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  2436. 'excellon_tooldia', 'excellon_endz', 'cncjob_tooldia',
  2437. 'geometry_cutz', 'geometry_travelz', 'geometry_feedrate', 'geometry_feedrate_rapid',
  2438. 'geometry_cnctooldia', 'tools_painttooldia', 'tools_paintoverlap', 'geometry_toolchangexy',
  2439. 'geometry_toolchangez',
  2440. 'tools_paintmargin', 'geometry_endz', 'geometry_depthperpass', 'global_gridx', 'global_gridy']
  2441. def scale_options(sfactor):
  2442. for dim in dimensions:
  2443. if dim == 'excellon_toolchangexy':
  2444. coords_xy = [float(eval(a)) for a in self.defaults["excellon_toolchangexy"].split(",")]
  2445. coords_xy[0] *= sfactor
  2446. coords_xy[1] *= sfactor
  2447. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2448. elif dim == 'geometry_toolchangexy':
  2449. coords_xy = [float(eval(a)) for a in self.defaults["geometry_toolchangexy"].split(",")]
  2450. coords_xy[0] *= sfactor
  2451. coords_xy[1] *= sfactor
  2452. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2453. else:
  2454. self.options[dim] *= sfactor
  2455. # The scaling factor depending on choice of units.
  2456. factor = 1/25.4
  2457. if self.general_options_form.general_app_group.units_radio.get_value().upper() == 'MM':
  2458. factor = 25.4
  2459. # Changing project units. Warn user.
  2460. msgbox = QtWidgets.QMessageBox()
  2461. msgbox.setText("<B>Change project units ...</B>")
  2462. msgbox.setInformativeText("Changing the units of the project causes all geometrical "
  2463. "properties of all objects to be scaled accordingly. Continue?")
  2464. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel | QtWidgets.QMessageBox.Ok)
  2465. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2466. response = msgbox.exec_()
  2467. if response == QtWidgets.QMessageBox.Ok:
  2468. self.options_read_form()
  2469. scale_options(factor)
  2470. self.options_write_form()
  2471. self.should_we_save = True
  2472. # change this only if the workspace is active
  2473. if self.defaults['global_workspace'] is True:
  2474. self.plotcanvas.draw_workspace()
  2475. # adjust the grid values on the main toolbar
  2476. self.ui.grid_gap_x_entry.set_value(float(self.ui.grid_gap_x_entry.get_value()) * factor)
  2477. self.ui.grid_gap_y_entry.set_value(float(self.ui.grid_gap_y_entry.get_value()) * factor)
  2478. for obj in self.collection.get_list():
  2479. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  2480. obj.convert_units(units)
  2481. # make that the properties stored in the object are also updated
  2482. self.object_changed.emit(obj)
  2483. obj.build_ui()
  2484. current = self.collection.get_active()
  2485. if current is not None:
  2486. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  2487. if not isinstance(current, FlatCAMGeometry):
  2488. current.to_form()
  2489. self.plot_all()
  2490. self.inform.emit("[success]Converted units to %s" % self.options["units"])
  2491. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  2492. self.set_screen_units(self.options["units"])
  2493. else:
  2494. # Undo toggling
  2495. self.toggle_units_ignore = True
  2496. if self.general_options_form.general_app_group.units_radio.get_value().upper() == 'MM':
  2497. self.general_options_form.general_app_group.units_radio.set_value('IN')
  2498. else:
  2499. self.general_options_form.general_app_group.units_radio.set_value('MM')
  2500. self.toggle_units_ignore = False
  2501. self.inform.emit("[WARNING_NOTCL]Units conversion cancelled.")
  2502. self.options_read_form()
  2503. def on_toggle_units_click(self):
  2504. if self.options["units"] == 'MM':
  2505. self.general_options_form.general_app_group.units_radio.set_value("IN")
  2506. else:
  2507. self.general_options_form.general_app_group.units_radio.set_value("MM")
  2508. self.on_toggle_units()
  2509. def on_language_apply(self):
  2510. self.report_usage("on_language_apply()")
  2511. # TODO: apply the language
  2512. # app restart section
  2513. pass
  2514. def on_fullscreen(self):
  2515. self.report_usage("on_fullscreen()")
  2516. if self.toggle_fscreen is False:
  2517. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  2518. tb.setVisible(False)
  2519. self.ui.splitter_left.setVisible(False)
  2520. self.toggle_fscreen = True
  2521. else:
  2522. self.restore_toolbar_view()
  2523. self.ui.splitter_left.setVisible(True)
  2524. self.toggle_fscreen = False
  2525. def on_toggle_plotarea(self):
  2526. self.report_usage("on_toggle_plotarea()")
  2527. try:
  2528. name = self.ui.plot_tab_area.widget(0).objectName()
  2529. except AttributeError:
  2530. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  2531. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  2532. self.ui.plot_tab_area.protectTab(0)
  2533. return
  2534. if name != 'plotarea':
  2535. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  2536. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  2537. self.ui.plot_tab_area.protectTab(0)
  2538. else:
  2539. self.ui.plot_tab_area.closeTab(0)
  2540. def on_toggle_notebook(self):
  2541. if self.ui.splitter.sizes()[0] == 0:
  2542. self.ui.splitter.setSizes([1, 1])
  2543. else:
  2544. self.ui.splitter.setSizes([0, 1])
  2545. def on_toggle_axis(self):
  2546. self.report_usage("on_toggle_axis()")
  2547. if self.toggle_axis is False:
  2548. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  2549. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  2550. self.plotcanvas.redraw()
  2551. self.toggle_axis = True
  2552. else:
  2553. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  2554. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  2555. self.plotcanvas.redraw()
  2556. self.toggle_axis = False
  2557. def on_toggle_grid(self):
  2558. self.report_usage("on_toggle_grid()")
  2559. self.ui.grid_snap_btn.trigger()
  2560. def on_options_combo_change(self, sel):
  2561. """
  2562. Called when the combo box to choose between application defaults and
  2563. project option changes value. The corresponding variables are
  2564. copied to the UI.
  2565. :param sel: The option index that was chosen.
  2566. :return: None
  2567. """
  2568. # combo_sel = self.ui.notebook.combo_options.get_active()
  2569. App.log.debug("Options --> %s" % sel)
  2570. # form = [self.defaults_form, self.options_form][sel]
  2571. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  2572. if sel == 0:
  2573. self.gen_form = self.general_defaults_form
  2574. self.ger_form = self.gerber_defaults_form
  2575. self.exc_form = self.excellon_defaults_form
  2576. self.geo_form = self.geometry_defaults_form
  2577. self.cnc_form = self.cncjob_defaults_form
  2578. self.tools_form = self.tools_defaults_form
  2579. elif sel == 1:
  2580. self.gen_form = self.general_options_form
  2581. self.ger_form = self.gerber_options_form
  2582. self.exc_form = self.excellon_options_form
  2583. self.geo_form = self.geometry_options_form
  2584. self.cnc_form = self.cncjob_options_form
  2585. self.tools_form = self.tools_options_form
  2586. else:
  2587. return
  2588. try:
  2589. self.ui.general_scroll_area.takeWidget()
  2590. except:
  2591. self.log.debug("Nothing to remove")
  2592. self.ui.general_scroll_area.setWidget(self.gen_form)
  2593. self.gen_form.show()
  2594. try:
  2595. self.ui.gerber_scroll_area.takeWidget()
  2596. except:
  2597. self.log.debug("Nothing to remove")
  2598. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  2599. self.ger_form.show()
  2600. try:
  2601. self.ui.excellon_scroll_area.takeWidget()
  2602. except:
  2603. self.log.debug("Nothing to remove")
  2604. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  2605. self.exc_form.show()
  2606. try:
  2607. self.ui.geometry_scroll_area.takeWidget()
  2608. except:
  2609. self.log.debug("Nothing to remove")
  2610. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  2611. self.geo_form.show()
  2612. try:
  2613. self.ui.cncjob_scroll_area.takeWidget()
  2614. except:
  2615. self.log.debug("Nothing to remove")
  2616. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  2617. self.cnc_form.show()
  2618. try:
  2619. self.ui.tools_scroll_area.takeWidget()
  2620. except:
  2621. self.log.debug("Nothing to remove")
  2622. self.ui.tools_scroll_area.setWidget(self.tools_form)
  2623. self.tools_form.show()
  2624. self.log.debug("Finished GUI form initialization.")
  2625. # self.options2form()
  2626. def on_excellon_defaults_button(self):
  2627. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  2628. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  2629. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  2630. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  2631. self.defaults_form_fields["excellon_zeros"].set_value('L')
  2632. self.defaults_form_fields["excellon_units"].set_value('INCH')
  2633. log.debug("Excellon app defaults loaded ...")
  2634. def on_excellon_options_button(self):
  2635. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  2636. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  2637. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  2638. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  2639. self.options_form_fields["excellon_zeros"].set_value('L')
  2640. self.options_form_fields["excellon_units"].set_value('INCH')
  2641. log.debug("Excellon options defaults loaded ...")
  2642. # Setting plot colors handlers
  2643. def on_pf_color_entry(self):
  2644. self.defaults['global_plot_fill'] = self.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  2645. self.defaults['global_plot_fill'][7:9]
  2646. self.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  2647. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  2648. def on_pf_color_button(self):
  2649. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  2650. c_dialog = QtWidgets.QColorDialog()
  2651. plot_fill_color = c_dialog.getColor(initial=current_color)
  2652. if plot_fill_color.isValid() is False:
  2653. return
  2654. self.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  2655. "background-color:%s" % str(plot_fill_color.name()))
  2656. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  2657. self.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  2658. self.defaults['global_plot_fill'] = new_val
  2659. def on_pf_color_spinner(self):
  2660. spinner_value = self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  2661. self.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  2662. self.defaults['global_plot_fill'] = self.defaults['global_plot_fill'][:7] + \
  2663. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2664. self.defaults['global_plot_line'] = self.defaults['global_plot_line'][:7] + \
  2665. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2666. def on_pf_color_slider(self):
  2667. slider_value = self.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  2668. self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  2669. def on_pl_color_entry(self):
  2670. self.defaults['global_plot_line'] = self.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  2671. self.defaults['global_plot_line'][7:9]
  2672. self.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  2673. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  2674. def on_pl_color_button(self):
  2675. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  2676. # print(current_color)
  2677. c_dialog = QtWidgets.QColorDialog()
  2678. plot_line_color = c_dialog.getColor(initial=current_color)
  2679. if plot_line_color.isValid() is False:
  2680. return
  2681. self.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  2682. "background-color:%s" % str(plot_line_color.name()))
  2683. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  2684. self.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  2685. self.defaults['global_plot_line'] = new_val_line
  2686. # Setting selection colors (left - right) handlers
  2687. def on_sf_color_entry(self):
  2688. self.defaults['global_sel_fill'] = self.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  2689. self.defaults['global_sel_fill'][7:9]
  2690. self.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  2691. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  2692. def on_sf_color_button(self):
  2693. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  2694. c_dialog = QtWidgets.QColorDialog()
  2695. plot_fill_color = c_dialog.getColor(initial=current_color)
  2696. if plot_fill_color.isValid() is False:
  2697. return
  2698. self.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  2699. "background-color:%s" % str(plot_fill_color.name()))
  2700. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  2701. self.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  2702. self.defaults['global_sel_fill'] = new_val
  2703. def on_sf_color_spinner(self):
  2704. spinner_value = self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  2705. self.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  2706. self.defaults['global_sel_fill'] = self.defaults['global_sel_fill'][:7] + \
  2707. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2708. self.defaults['global_sel_line'] = self.defaults['global_sel_line'][:7] + \
  2709. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2710. def on_sf_color_slider(self):
  2711. slider_value = self.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  2712. self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  2713. def on_sl_color_entry(self):
  2714. self.defaults['global_sel_line'] = self.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  2715. self.defaults['global_sel_line'][7:9]
  2716. self.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  2717. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  2718. def on_sl_color_button(self):
  2719. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  2720. c_dialog = QtWidgets.QColorDialog()
  2721. plot_line_color = c_dialog.getColor(initial=current_color)
  2722. if plot_line_color.isValid() is False:
  2723. return
  2724. self.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  2725. "background-color:%s" % str(plot_line_color.name()))
  2726. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  2727. self.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  2728. self.defaults['global_sel_line'] = new_val_line
  2729. # Setting selection colors (right - left) handlers
  2730. def on_alt_sf_color_entry(self):
  2731. self.defaults['global_alt_sel_fill'] = self.general_defaults_form.general_gui_group \
  2732. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  2733. self.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  2734. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  2735. def on_alt_sf_color_button(self):
  2736. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  2737. c_dialog = QtWidgets.QColorDialog()
  2738. plot_fill_color = c_dialog.getColor(initial=current_color)
  2739. if plot_fill_color.isValid() is False:
  2740. return
  2741. self.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  2742. "background-color:%s" % str(plot_fill_color.name()))
  2743. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  2744. self.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  2745. self.defaults['global_alt_sel_fill'] = new_val
  2746. def on_alt_sf_color_spinner(self):
  2747. spinner_value = self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  2748. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  2749. self.defaults['global_alt_sel_fill'] = self.defaults['global_alt_sel_fill'][:7] + \
  2750. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2751. self.defaults['global_alt_sel_line'] = self.defaults['global_alt_sel_line'][:7] + \
  2752. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2753. def on_alt_sf_color_slider(self):
  2754. slider_value = self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  2755. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  2756. def on_alt_sl_color_entry(self):
  2757. self.defaults['global_alt_sel_line'] = self.general_defaults_form.general_gui_group \
  2758. .alt_sl_color_entry.get_value()[:7] + self.defaults['global_alt_sel_line'][7:9]
  2759. self.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  2760. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  2761. def on_alt_sl_color_button(self):
  2762. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  2763. c_dialog = QtWidgets.QColorDialog()
  2764. plot_line_color = c_dialog.getColor(initial=current_color)
  2765. if plot_line_color.isValid() is False:
  2766. return
  2767. self.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  2768. "background-color:%s" % str(plot_line_color.name()))
  2769. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  2770. self.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  2771. self.defaults['global_alt_sel_line'] = new_val_line
  2772. # Setting Editor colors
  2773. def on_draw_color_entry(self):
  2774. self.defaults['global_draw_color'] = self.general_defaults_form.general_gui_group \
  2775. .draw_color_entry.get_value()
  2776. self.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  2777. "background-color:%s" % str(self.defaults['global_draw_color']))
  2778. def on_draw_color_button(self):
  2779. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  2780. c_dialog = QtWidgets.QColorDialog()
  2781. draw_color = c_dialog.getColor(initial=current_color)
  2782. if draw_color.isValid() is False:
  2783. return
  2784. self.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  2785. "background-color:%s" % str(draw_color.name()))
  2786. new_val = str(draw_color.name())
  2787. self.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  2788. self.defaults['global_draw_color'] = new_val
  2789. def on_sel_draw_color_entry(self):
  2790. self.defaults['global_sel_draw_color'] = self.general_defaults_form.general_gui_group \
  2791. .sel_draw_color_entry.get_value()
  2792. self.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  2793. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  2794. def on_sel_draw_color_button(self):
  2795. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  2796. c_dialog = QtWidgets.QColorDialog()
  2797. sel_draw_color = c_dialog.getColor(initial=current_color)
  2798. if sel_draw_color.isValid() is False:
  2799. return
  2800. self.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  2801. "background-color:%s" % str(sel_draw_color.name()))
  2802. new_val_sel = str(sel_draw_color.name())
  2803. self.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  2804. self.defaults['global_sel_draw_color'] = new_val_sel
  2805. def on_deselect_all(self):
  2806. self.collection.set_all_inactive()
  2807. self.delete_selection_shape()
  2808. def on_workspace_modified(self):
  2809. self.save_defaults(silent=True)
  2810. self.plotcanvas.draw_workspace()
  2811. def on_workspace(self):
  2812. self.report_usage("on_workspace()")
  2813. if self.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  2814. self.plotcanvas.restore_workspace()
  2815. else:
  2816. self.plotcanvas.delete_workspace()
  2817. self.save_defaults(silent=True)
  2818. def on_workspace_menu(self):
  2819. if self.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  2820. self.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  2821. else:
  2822. self.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  2823. self.on_workspace()
  2824. def on_layout(self, index, lay=None):
  2825. self.report_usage("on_layout()")
  2826. if lay:
  2827. current_layout = lay
  2828. else:
  2829. current_layout = self.general_defaults_form.general_gui_set_group.layout_combo.get_value().lower()
  2830. settings = QSettings("Open Source", "FlatCAM")
  2831. settings.setValue('layout', current_layout)
  2832. # This will write the setting to the platform specific storage.
  2833. del settings
  2834. # first remove the toolbars:
  2835. self.ui.removeToolBar(self.ui.toolbarfile)
  2836. self.ui.removeToolBar(self.ui.toolbargeo)
  2837. self.ui.removeToolBar(self.ui.toolbarview)
  2838. self.ui.removeToolBar(self.ui.toolbartools)
  2839. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  2840. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  2841. self.ui.removeToolBar(self.ui.snap_toolbar)
  2842. if current_layout == 'standard':
  2843. ### TOOLBAR INSTALLATION ###
  2844. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  2845. self.ui.toolbarfile.setObjectName('File_TB')
  2846. self.ui.addToolBar(self.ui.toolbarfile)
  2847. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  2848. self.ui.toolbargeo.setObjectName('Edit_TB')
  2849. self.ui.addToolBar(self.ui.toolbargeo)
  2850. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  2851. self.ui.toolbarview.setObjectName('View_TB')
  2852. self.ui.addToolBar(self.ui.toolbarview)
  2853. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  2854. self.ui.toolbartools.setObjectName('Tools_TB')
  2855. self.ui.addToolBar(self.ui.toolbartools)
  2856. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  2857. self.ui.exc_edit_toolbar.setVisible(False)
  2858. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  2859. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  2860. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  2861. self.ui.geo_edit_toolbar.setVisible(False)
  2862. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  2863. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  2864. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  2865. self.ui.snap_toolbar.setObjectName('Snap_TB')
  2866. # self.ui.snap_toolbar.setMaximumHeight(30)
  2867. self.ui.addToolBar(self.ui.snap_toolbar)
  2868. self.ui.corner_snap_btn.setVisible(False)
  2869. self.ui.snap_magnet.setVisible(False)
  2870. elif current_layout == 'compact':
  2871. ### TOOLBAR INSTALLATION ###
  2872. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  2873. self.ui.toolbarfile.setObjectName('File_TB')
  2874. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  2875. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  2876. self.ui.toolbargeo.setObjectName('Edit_TB')
  2877. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  2878. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  2879. self.ui.toolbarview.setObjectName('View_TB')
  2880. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarview)
  2881. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  2882. self.ui.toolbartools.setObjectName('Tools_TB')
  2883. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  2884. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  2885. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  2886. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.exc_edit_toolbar)
  2887. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  2888. self.ui.geo_edit_toolbar.setVisible(False)
  2889. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  2890. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  2891. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  2892. self.ui.snap_toolbar.setObjectName('Snap_TB')
  2893. self.ui.snap_toolbar.setMaximumHeight(30)
  2894. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  2895. self.ui.corner_snap_btn.setVisible(True)
  2896. self.ui.snap_magnet.setVisible(True)
  2897. self.ui.populate_toolbars()
  2898. self.ui.grid_snap_btn.setChecked(True)
  2899. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  2900. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  2901. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  2902. self.ui.grid_gap_link_cb.setChecked(True)
  2903. def on_save_button(self):
  2904. self.save_defaults(silent=False)
  2905. # load the defaults so they are updated into the app
  2906. self.load_defaults(filename='current_defaults')
  2907. # Re-fresh project options
  2908. self.on_options_app2project()
  2909. def handleOpen(self):
  2910. self.report_usage("handleOpen()")
  2911. filter_group = " G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  2912. "All Files (*.*)"
  2913. path, _ = QtWidgets.QFileDialog.getOpenFileName(
  2914. caption='Open file', directory=self.get_last_folder(), filter=filter_group)
  2915. if path:
  2916. file = QtCore.QFile(path)
  2917. if file.open(QtCore.QIODevice.ReadOnly):
  2918. stream = QtCore.QTextStream(file)
  2919. self.gcode_edited = stream.readAll()
  2920. self.ui.code_editor.setPlainText(self.gcode_edited)
  2921. file.close()
  2922. def handlePrint(self):
  2923. self.report_usage("handlePrint()")
  2924. dialog = QtPrintSupport.QPrintDialog()
  2925. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  2926. self.ui.code_editor.document().print_(dialog.printer())
  2927. def handlePreview(self):
  2928. self.report_usage("handlePreview()")
  2929. dialog = QtPrintSupport.QPrintPreviewDialog()
  2930. dialog.paintRequested.connect(self.ui.code_editor.print_)
  2931. dialog.exec_()
  2932. def handleTextChanged(self):
  2933. self.report_usage("handleTextChanged()")
  2934. # enable = not self.ui.code_editor.document().isEmpty()
  2935. # self.ui.buttonPrint.setEnabled(enable)
  2936. # self.ui.buttonPreview.setEnabled(enable)
  2937. pass
  2938. def handleSaveGCode(self):
  2939. self.report_usage("handleSaveGCode()")
  2940. obj_name = self.collection.get_active().options['name']
  2941. _filter_ = " G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  2942. "All Files (*.*)"
  2943. try:
  2944. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  2945. caption="Export G-Code ...",
  2946. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  2947. filter=_filter_
  2948. )[0])
  2949. except TypeError:
  2950. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption="Export G-Code ...", filter=_filter_)[0])
  2951. if filename == "":
  2952. self.inform.emit("[WARNING_NOTCL]Export CNC Code cancelled.")
  2953. return
  2954. else:
  2955. try:
  2956. my_gcode = self.ui.code_editor.toPlainText()
  2957. with open(filename, 'w') as f:
  2958. for line in my_gcode:
  2959. f.write(line)
  2960. except FileNotFoundError:
  2961. self.inform.emit("[WARNING] No such file or directory")
  2962. return
  2963. # Just for adding it to the recent files list.
  2964. self.file_opened.emit("cncjob", filename)
  2965. self.file_saved.emit("cncjob", filename)
  2966. self.inform.emit("Saved to: " + filename)
  2967. def handleFindGCode(self):
  2968. self.report_usage("handleFindGCode()")
  2969. flags = QtGui.QTextDocument.FindCaseSensitively
  2970. text_to_be_found = self.ui.entryFind.get_value()
  2971. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  2972. if r is False:
  2973. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  2974. def handleReplaceGCode(self):
  2975. self.report_usage("handleReplaceGCode()")
  2976. old = self.ui.entryFind.get_value()
  2977. new = self.ui.entryReplace.get_value()
  2978. if self.ui.sel_all_cb.isChecked():
  2979. while True:
  2980. cursor = self.ui.code_editor.textCursor()
  2981. cursor.beginEditBlock()
  2982. flags = QtGui.QTextDocument.FindCaseSensitively
  2983. # self.ui.editor is the QPlainTextEdit
  2984. r = self.ui.code_editor.find(str(old), flags)
  2985. if r:
  2986. qc = self.ui.code_editor.textCursor()
  2987. if qc.hasSelection():
  2988. qc.insertText(new)
  2989. else:
  2990. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  2991. break
  2992. # Mark end of undo block
  2993. cursor.endEditBlock()
  2994. else:
  2995. cursor = self.ui.code_editor.textCursor()
  2996. cursor.beginEditBlock()
  2997. qc = self.ui.code_editor.textCursor()
  2998. if qc.hasSelection():
  2999. qc.insertText(new)
  3000. # Mark end of undo block
  3001. cursor.endEditBlock()
  3002. def on_tool_add_keypress(self):
  3003. ## Current application units in Upper Case
  3004. self.units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  3005. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3006. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3007. if notebook_widget_name == 'selected_tab':
  3008. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  3009. # Tool add works for Geometry only if Advanced is True in Preferences
  3010. if self.defaults["global_advanced"] is True:
  3011. tool_add_popup = FCInputDialog(title="New Tool ...",
  3012. text='Enter a Tool Diameter:',
  3013. min=0.0000, max=99.9999, decimals=4)
  3014. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  3015. val, ok = tool_add_popup.get_value()
  3016. if ok:
  3017. if float(val) == 0:
  3018. self.inform.emit(
  3019. "[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format.")
  3020. return
  3021. self.collection.get_active().on_tool_add(dia=float(val))
  3022. else:
  3023. self.inform.emit(
  3024. "[WARNING_NOTCL] Adding Tool cancelled ...")
  3025. else:
  3026. msgbox = QtWidgets.QMessageBox()
  3027. msgbox.setText("Adding Tool works only when Advanced is checked.\n"
  3028. "Go to Preferences -> General - Show Advanced Options.")
  3029. msgbox.setWindowTitle("Tool adding ...")
  3030. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  3031. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3032. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3033. msgbox.exec_()
  3034. # work only if the notebook tab on focus is the Tools_Tab
  3035. if notebook_widget_name == 'tool_tab':
  3036. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3037. tool_add_popup = FCInputDialog(title="New Tool ...",
  3038. text='Enter a Tool Diameter:',
  3039. min=0.0000, max=99.9999, decimals=4)
  3040. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  3041. val, ok = tool_add_popup.get_value()
  3042. # and only if the tool is NCC Tool
  3043. if tool_widget == self.ncclear_tool.toolName:
  3044. if ok:
  3045. if float(val) == 0:
  3046. self.inform.emit(
  3047. "[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format.")
  3048. return
  3049. self.ncclear_tool.on_tool_add(dia=float(val))
  3050. else:
  3051. self.inform.emit(
  3052. "[WARNING_NOTCL] Adding Tool cancelled ...")
  3053. # and only if the tool is Paint Area Tool
  3054. elif tool_widget == self.paint_tool.toolName:
  3055. if ok:
  3056. if float(val) == 0:
  3057. self.inform.emit(
  3058. "[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format.")
  3059. return
  3060. self.paint_tool.on_tool_add(dia=float(val))
  3061. else:
  3062. self.inform.emit(
  3063. "[WARNING_NOTCL] Adding Tool cancelled ...")
  3064. # and only if the tool is Solder Paste Dispensing Tool
  3065. elif tool_widget == self.paste_tool.toolName:
  3066. if ok:
  3067. if float(val) == 0:
  3068. self.inform.emit(
  3069. "[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format.")
  3070. return
  3071. self.paste_tool.on_tool_add(dia=float(val))
  3072. else:
  3073. self.inform.emit(
  3074. "[WARNING_NOTCL] Adding Tool cancelled ...")
  3075. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3076. # See description bellow.
  3077. def on_delete_keypress(self):
  3078. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3079. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3080. if notebook_widget_name == 'selected_tab':
  3081. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  3082. self.collection.get_active().on_tool_delete()
  3083. # work only if the notebook tab on focus is the Tools_Tab
  3084. elif notebook_widget_name == 'tool_tab':
  3085. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3086. # and only if the tool is NCC Tool
  3087. if tool_widget == self.ncclear_tool.toolName:
  3088. self.ncclear_tool.on_tool_delete()
  3089. # and only if the tool is Paint Tool
  3090. elif tool_widget == self.paint_tool.toolName:
  3091. self.paint_tool.on_tool_delete()
  3092. # and only if the tool is Solder Paste Dispensing Tool
  3093. elif tool_widget == self.paste_tool.toolName:
  3094. self.paste_tool.on_tool_delete()
  3095. else:
  3096. self.on_delete()
  3097. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3098. # some screens you have to be careful where you hover with your mouse.
  3099. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3100. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3101. # Complicated, I know :)
  3102. def on_delete(self):
  3103. """
  3104. Delete the currently selected FlatCAMObjs.
  3105. :return: None
  3106. """
  3107. self.report_usage("on_delete()")
  3108. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3109. # a geometry object before we update it.
  3110. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False:
  3111. if self.collection.get_active():
  3112. self.log.debug("on_delete()")
  3113. self.report_usage("on_delete")
  3114. while (self.collection.get_active()):
  3115. self.delete_first_selected()
  3116. self.inform.emit("Object(s) deleted ...")
  3117. # make sure that the selection shape is deleted, too
  3118. self.delete_selection_shape()
  3119. else:
  3120. self.inform.emit("Failed. No object(s) selected...")
  3121. else:
  3122. self.inform.emit("Save the work in Editor and try again ...")
  3123. def on_set_origin(self):
  3124. """
  3125. Set the origin to the left mouse click position
  3126. :return: None
  3127. """
  3128. #display the message for the user
  3129. #and ask him to click on the desired position
  3130. self.report_usage("on_set_origin()")
  3131. self.inform.emit('Click to set the origin ...')
  3132. self.plotcanvas.vis_connect('mouse_press', self.on_set_zero_click)
  3133. def on_jump_to(self):
  3134. """
  3135. Jump to a location by setting the mouse cursor location
  3136. :return:
  3137. """
  3138. self.report_usage("on_jump_to()")
  3139. dia_box = Dialog_box(title="Jump to ...",
  3140. label="Enter the coordinates in format X,Y:",
  3141. icon=QtGui.QIcon('share/jump_to16.png'))
  3142. if dia_box.ok is True:
  3143. try:
  3144. location = eval(dia_box.location)
  3145. if not isinstance(location, tuple):
  3146. self.inform.emit("Wrong coordinates. Enter coordinates in format: X,Y")
  3147. return
  3148. except:
  3149. return
  3150. else:
  3151. return
  3152. self.plotcanvas.fit_center(loc=location)
  3153. cursor = QtGui.QCursor()
  3154. canvas_origin = self.plotcanvas.vispy_canvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3155. jump_loc = self.plotcanvas.vispy_canvas.translate_coords_2((location[0], location[1]))
  3156. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  3157. self.inform.emit("Done.")
  3158. def on_copy_object(self):
  3159. self.report_usage("on_copy_object()")
  3160. def initialize(obj_init, app):
  3161. obj_init.solid_geometry = obj.solid_geometry
  3162. try:
  3163. if obj.tools:
  3164. obj_init.tools = obj.tools
  3165. except Exception as e:
  3166. log.debug("on_copy_object() --> %s" % str(e))
  3167. def initialize_excellon(obj_init, app):
  3168. obj_init.tools = obj.tools
  3169. # drills are offset, so they need to be deep copied
  3170. obj_init.drills = deepcopy(obj.drills)
  3171. # slots are offset, so they need to be deep copied
  3172. obj_init.slots = deepcopy(obj.slots)
  3173. obj_init.create_geometry()
  3174. for obj in self.collection.get_selected():
  3175. obj_name = obj.options["name"]
  3176. try:
  3177. if isinstance(obj, FlatCAMExcellon):
  3178. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  3179. elif isinstance(obj,FlatCAMGerber):
  3180. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  3181. elif isinstance(obj,FlatCAMGeometry):
  3182. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  3183. except Exception as e:
  3184. return "Operation failed: %s" % str(e)
  3185. def on_copy_object2(self, custom_name):
  3186. def initialize_geometry(obj_init, app):
  3187. obj_init.solid_geometry = obj.solid_geometry
  3188. try:
  3189. if obj.tools:
  3190. obj_init.tools = obj.tools
  3191. except Exception as e:
  3192. log.debug("on_copy_object2() --> %s" % str(e))
  3193. def initialize_gerber(obj_init, app):
  3194. obj_init.solid_geometry = obj.solid_geometry
  3195. obj_init.apertures = deepcopy(obj.apertures)
  3196. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  3197. def initialize_excellon(obj_init, app):
  3198. obj_init.tools = obj.tools
  3199. # drills are offset, so they need to be deep copied
  3200. obj_init.drills = deepcopy(obj.drills)
  3201. # slots are offset, so they need to be deep copied
  3202. obj_init.slots = deepcopy(obj.slots)
  3203. obj_init.create_geometry()
  3204. for obj in self.collection.get_selected():
  3205. obj_name = obj.options["name"]
  3206. try:
  3207. if isinstance(obj, FlatCAMExcellon):
  3208. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  3209. elif isinstance(obj,FlatCAMGerber):
  3210. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  3211. elif isinstance(obj,FlatCAMGeometry):
  3212. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  3213. except Exception as e:
  3214. return "Operation failed: %s" % str(e)
  3215. def on_rename_object(self, text):
  3216. self.report_usage("on_rename_object()")
  3217. named_obj = self.collection.get_active()
  3218. for obj in named_obj:
  3219. if obj is list:
  3220. self.on_rename_object(text)
  3221. else:
  3222. try:
  3223. obj.options['name'] = text
  3224. except:
  3225. log.warning("Could not rename the object in the list")
  3226. def on_copy_object_as_geometry(self):
  3227. self.report_usage("on_copy_object_as_geometry()")
  3228. def initialize(obj_init, app):
  3229. obj_init.solid_geometry = obj.solid_geometry
  3230. if obj.tools:
  3231. obj_init.tools = obj.tools
  3232. def initialize_excellon(obj, app):
  3233. objs = self.collection.get_selected()
  3234. FlatCAMGeometry.merge(objs, obj)
  3235. for obj in self.collection.get_selected():
  3236. obj_name = obj.options["name"]
  3237. try:
  3238. if isinstance(obj, FlatCAMExcellon):
  3239. self.new_object("geometry", str(obj_name) + "_gcopy", initialize_excellon)
  3240. else:
  3241. self.new_object("geometry", str(obj_name) + "_gcopy", initialize)
  3242. except Exception as e:
  3243. return "Operation failed: %s" % str(e)
  3244. def on_set_zero_click(self, event):
  3245. #this function will be available only for mouse left click
  3246. pos =[]
  3247. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3248. if event.button == 1:
  3249. if self.grid_status() == True:
  3250. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3251. else:
  3252. pos = pos_canvas
  3253. x = 0 - pos[0]
  3254. y = 0 - pos[1]
  3255. for obj in self.collection.get_list():
  3256. obj.offset((x,y))
  3257. self.object_changed.emit(obj)
  3258. # obj.plot()
  3259. self.plot_all(zoom=False)
  3260. self.inform.emit('[success] Origin set ...')
  3261. self.plotcanvas.vis_disconnect('mouse_press', self.on_set_zero_click)
  3262. self.should_we_save = True
  3263. def on_selectall(self):
  3264. self.report_usage("on_selectall()")
  3265. # delete the possible selection box around a possible selected object
  3266. self.delete_selection_shape()
  3267. for name in self.collection.get_names():
  3268. self.collection.set_active(name)
  3269. curr_sel_obj = self.collection.get_by_name(name)
  3270. # create the selection box around the selected object
  3271. self.draw_selection_shape(curr_sel_obj)
  3272. def on_preferences(self):
  3273. # add the tab if it was closed
  3274. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, "Preferences")
  3275. # delete the absolute and relative position and messages in the infobar
  3276. self.ui.position_label.setText("")
  3277. self.ui.rel_position_label.setText("")
  3278. # Switch plot_area to preferences page
  3279. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  3280. self.ui.show()
  3281. def on_flipy(self):
  3282. self.report_usage("on_flipy()")
  3283. obj_list = self.collection.get_selected()
  3284. xminlist = []
  3285. yminlist = []
  3286. xmaxlist = []
  3287. ymaxlist = []
  3288. if not obj_list:
  3289. self.inform.emit("[WARNING_NOTCL] No object selected to Flip on Y axis.")
  3290. else:
  3291. try:
  3292. # first get a bounding box to fit all
  3293. for obj in obj_list:
  3294. xmin, ymin, xmax, ymax = obj.bounds()
  3295. xminlist.append(xmin)
  3296. yminlist.append(ymin)
  3297. xmaxlist.append(xmax)
  3298. ymaxlist.append(ymax)
  3299. # get the minimum x,y and maximum x,y for all objects selected
  3300. xminimal = min(xminlist)
  3301. yminimal = min(yminlist)
  3302. xmaximal = max(xmaxlist)
  3303. ymaximal = max(ymaxlist)
  3304. px = 0.5 * (xminimal + xmaximal)
  3305. py = 0.5 * (yminimal + ymaximal)
  3306. # execute mirroring
  3307. for obj in obj_list:
  3308. obj.mirror('X', [px, py])
  3309. obj.plot()
  3310. self.object_changed.emit(obj)
  3311. self.inform.emit("[success] Flip on Y axis done.")
  3312. except Exception as e:
  3313. self.inform.emit("[ERROR_NOTCL] Due of %s, Flip action was not executed." % str(e))
  3314. return
  3315. def on_flipx(self):
  3316. self.report_usage("on_flipx()")
  3317. obj_list = self.collection.get_selected()
  3318. xminlist = []
  3319. yminlist = []
  3320. xmaxlist = []
  3321. ymaxlist = []
  3322. if not obj_list:
  3323. self.inform.emit("[WARNING_NOTCL] No object selected to Flip on X axis.")
  3324. else:
  3325. try:
  3326. # first get a bounding box to fit all
  3327. for obj in obj_list:
  3328. xmin, ymin, xmax, ymax = obj.bounds()
  3329. xminlist.append(xmin)
  3330. yminlist.append(ymin)
  3331. xmaxlist.append(xmax)
  3332. ymaxlist.append(ymax)
  3333. # get the minimum x,y and maximum x,y for all objects selected
  3334. xminimal = min(xminlist)
  3335. yminimal = min(yminlist)
  3336. xmaximal = max(xmaxlist)
  3337. ymaximal = max(ymaxlist)
  3338. px = 0.5 * (xminimal + xmaximal)
  3339. py = 0.5 * (yminimal + ymaximal)
  3340. # execute mirroring
  3341. for obj in obj_list:
  3342. obj.mirror('Y', [px, py])
  3343. obj.plot()
  3344. self.object_changed.emit(obj)
  3345. self.inform.emit("[success] Flip on X axis done.")
  3346. except Exception as e:
  3347. self.inform.emit("[ERROR_NOTCL] Due of %s, Flip action was not executed." % str(e))
  3348. return
  3349. def on_rotate(self, silent=False, preset=None):
  3350. self.report_usage("on_rotate()")
  3351. obj_list = self.collection.get_selected()
  3352. xminlist = []
  3353. yminlist = []
  3354. xmaxlist = []
  3355. ymaxlist = []
  3356. if not obj_list:
  3357. self.inform.emit("[WARNING_NOTCL] No object selected to Rotate.")
  3358. else:
  3359. if silent is False:
  3360. rotatebox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  3361. min=-360, max=360, decimals=4,
  3362. init_val=float(self.defaults['tools_transform_rotate']))
  3363. num, ok = rotatebox.get_value()
  3364. else:
  3365. num = preset
  3366. ok = True
  3367. if ok:
  3368. try:
  3369. # first get a bounding box to fit all
  3370. for obj in obj_list:
  3371. xmin, ymin, xmax, ymax = obj.bounds()
  3372. xminlist.append(xmin)
  3373. yminlist.append(ymin)
  3374. xmaxlist.append(xmax)
  3375. ymaxlist.append(ymax)
  3376. # get the minimum x,y and maximum x,y for all objects selected
  3377. xminimal = min(xminlist)
  3378. yminimal = min(yminlist)
  3379. xmaximal = max(xmaxlist)
  3380. ymaximal = max(ymaxlist)
  3381. px = 0.5 * (xminimal + xmaximal)
  3382. py = 0.5 * (yminimal + ymaximal)
  3383. for sel_obj in obj_list:
  3384. sel_obj.rotate(-float(num), point=(px, py))
  3385. sel_obj.plot()
  3386. self.object_changed.emit(sel_obj)
  3387. self.inform.emit("[success] Rotation done.")
  3388. except Exception as e:
  3389. self.inform.emit("[ERROR_NOTCL] Due of %s, rotation movement was not executed." % str(e))
  3390. return
  3391. def on_skewx(self):
  3392. self.report_usage("on_skewx()")
  3393. obj_list = self.collection.get_selected()
  3394. xminlist = []
  3395. yminlist = []
  3396. if not obj_list:
  3397. self.inform.emit("[WARNING_NOTCL] No object selected to Skew/Shear on X axis.")
  3398. else:
  3399. skewxbox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  3400. min=-360, max=360, decimals=4,
  3401. init_val=float(self.defaults['tools_transform_skew_x']))
  3402. num, ok = skewxbox.get_value()
  3403. if ok:
  3404. # first get a bounding box to fit all
  3405. for obj in obj_list:
  3406. xmin, ymin, xmax, ymax = obj.bounds()
  3407. xminlist.append(xmin)
  3408. yminlist.append(ymin)
  3409. # get the minimum x,y and maximum x,y for all objects selected
  3410. xminimal = min(xminlist)
  3411. yminimal = min(yminlist)
  3412. for obj in obj_list:
  3413. obj.skew(num, 0, point=(xminimal, yminimal))
  3414. obj.plot()
  3415. self.object_changed.emit(obj)
  3416. self.inform.emit("[success] Skew on X axis done.")
  3417. def on_skewy(self):
  3418. self.report_usage("on_skewy()")
  3419. obj_list = self.collection.get_selected()
  3420. xminlist = []
  3421. yminlist = []
  3422. if not obj_list:
  3423. self.inform.emit("[WARNING_NOTCL] No object selected to Skew/Shear on Y axis.")
  3424. else:
  3425. skewybox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  3426. min=-360, max=360, decimals=4,
  3427. init_val=float(self.defaults['tools_transform_skew_y']))
  3428. num, ok = skewybox.get_value()
  3429. if ok:
  3430. # first get a bounding box to fit all
  3431. for obj in obj_list:
  3432. xmin, ymin, xmax, ymax = obj.bounds()
  3433. xminlist.append(xmin)
  3434. yminlist.append(ymin)
  3435. # get the minimum x,y and maximum x,y for all objects selected
  3436. xminimal = min(xminlist)
  3437. yminimal = min(yminlist)
  3438. for obj in obj_list:
  3439. obj.skew(0, num, point=(xminimal, yminimal))
  3440. obj.plot()
  3441. self.object_changed.emit(obj)
  3442. self.inform.emit("[success] Skew on Y axis done.")
  3443. def delete_first_selected(self):
  3444. # Keep this for later
  3445. try:
  3446. name = self.collection.get_active().options["name"]
  3447. except AttributeError:
  3448. self.log.debug("Nothing selected for deletion")
  3449. return
  3450. # Remove plot
  3451. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3452. # self.plotcanvas.auto_adjust_axes()
  3453. # Clear form
  3454. self.setup_component_editor()
  3455. # Remove from dictionary
  3456. self.collection.delete_active()
  3457. self.inform.emit("Object deleted: %s" % name)
  3458. def on_plots_updated(self):
  3459. """
  3460. Callback used to report when the plots have changed.
  3461. Adjust axes and zooms to fit.
  3462. :return: None
  3463. """
  3464. # self.plotcanvas.auto_adjust_axes()
  3465. self.plotcanvas.vispy_canvas.update() # TODO: Need update canvas?
  3466. self.on_zoom_fit(None)
  3467. # TODO: Rework toolbar 'clear', 'replot' functions
  3468. def on_toolbar_replot(self):
  3469. """
  3470. Callback for toolbar button. Re-plots all objects.
  3471. :return: None
  3472. """
  3473. self.report_usage("on_toolbar_replot")
  3474. self.log.debug("on_toolbar_replot()")
  3475. try:
  3476. self.collection.get_active().read_form()
  3477. except AttributeError:
  3478. self.log.debug("on_toolbar_replot(): AttributeError")
  3479. pass
  3480. self.plot_all()
  3481. def on_row_activated(self, index):
  3482. if index.isValid():
  3483. if index.internalPointer().parent_item != self.collection.root_item:
  3484. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3485. def grid_status(self):
  3486. if self.ui.grid_snap_btn.isChecked():
  3487. return 1
  3488. else:
  3489. return 0
  3490. def populate_cmenu_grids(self):
  3491. units = self.general_options_form.general_app_group.units_radio.get_value().lower()
  3492. self.ui.cmenu_gridmenu.clear()
  3493. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  3494. for grid in sorted_list:
  3495. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  3496. action.triggered.connect(self.set_grid)
  3497. self.ui.cmenu_gridmenu.addSeparator()
  3498. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), "Add")
  3499. grid_add.triggered.connect(self.on_grid_add)
  3500. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), "Delete")
  3501. grid_delete.triggered.connect(self.on_grid_delete)
  3502. def set_grid(self):
  3503. self.ui.grid_gap_x_entry.setText(self.sender().text())
  3504. self.ui.grid_gap_y_entry.setText(self.sender().text())
  3505. def on_grid_add(self):
  3506. ## Current application units in lower Case
  3507. units = self.general_options_form.general_app_group.units_radio.get_value().lower()
  3508. grid_add_popup = FCInputDialog(title="New Grid ...",
  3509. text='Enter a Grid VAlue:',
  3510. min=0.0000, max=99.9999, decimals=4)
  3511. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  3512. val, ok = grid_add_popup.get_value()
  3513. if ok:
  3514. if float(val) == 0:
  3515. self.inform.emit(
  3516. "[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format.")
  3517. return
  3518. else:
  3519. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  3520. self.defaults["global_grid_context_menu"][str(units)].append(val)
  3521. self.inform.emit(
  3522. "[success] New Grid added ...")
  3523. else:
  3524. self.inform.emit(
  3525. "[WARNING_NOTCL] Grid already exists ...")
  3526. else:
  3527. self.inform.emit(
  3528. "[WARNING_NOTCL] Adding New Grid cancelled ...")
  3529. def on_grid_delete(self):
  3530. ## Current application units in lower Case
  3531. units = self.general_options_form.general_app_group.units_radio.get_value().lower()
  3532. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  3533. text='Enter a Grid Value:',
  3534. min=0.0000, max=99.9999, decimals=4)
  3535. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  3536. val, ok = grid_del_popup.get_value()
  3537. if ok:
  3538. if float(val) == 0:
  3539. self.inform.emit(
  3540. "[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format.")
  3541. return
  3542. else:
  3543. try:
  3544. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  3545. except ValueError:
  3546. self.inform.emit(
  3547. "[ERROR_NOTCL] Grid Value does not exist ...")
  3548. return
  3549. self.inform.emit(
  3550. "[success] Grid Value deleted ...")
  3551. else:
  3552. self.inform.emit(
  3553. "[WARNING_NOTCL] Delete Grid value cancelled ...")
  3554. def on_shortcut_list(self):
  3555. self.report_usage("on_shortcut_list()")
  3556. # add the tab if it was closed
  3557. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, "Key Shortcut List")
  3558. # delete the absolute and relative position and messages in the infobar
  3559. self.ui.position_label.setText("")
  3560. self.ui.rel_position_label.setText("")
  3561. # Switch plot_area to preferences page
  3562. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  3563. self.ui.show()
  3564. def on_select_tab(self, name):
  3565. if name == 'project':
  3566. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  3567. elif name == 'selected':
  3568. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3569. elif name == 'tool':
  3570. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  3571. # if the splitter us hidden, display it
  3572. if self.ui.splitter.sizes()[0] == 0:
  3573. self.ui.splitter.setSizes([1, 1])
  3574. def on_copy_name(self):
  3575. self.report_usage("on_copy_name()")
  3576. obj = self.collection.get_active()
  3577. try:
  3578. name = obj.options["name"]
  3579. except AttributeError:
  3580. log.debug("on_copy_name() --> No object selected to copy it's name")
  3581. self.inform.emit("[WARNING_NOTCL]No object selected to copy it's name")
  3582. return
  3583. self.clipboard.setText(name)
  3584. self.inform.emit("Name copied on clipboard ...")
  3585. def on_mouse_click_over_plot(self, event):
  3586. """
  3587. Callback for the mouse click event over the plot. This event is generated
  3588. by the Matplotlib backend and has been registered in ``self.__init__()``.
  3589. For details, see: http://matplotlib.org/users/event_handling.html
  3590. Default actions are:
  3591. * Copy coordinates to clipboard. Ex.: (65.5473, -13.2679)
  3592. :param event: Contains information about the event, like which button
  3593. was clicked, the pixel coordinates and the axes coordinates.
  3594. :return: None
  3595. """
  3596. self.pos = []
  3597. # So it can receive key presses
  3598. self.plotcanvas.vispy_canvas.native.setFocus()
  3599. # Set the mouse button for panning
  3600. self.plotcanvas.vispy_canvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  3601. self.pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3602. if self.grid_status() == True:
  3603. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  3604. self.app_cursor.enabled = True
  3605. else:
  3606. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  3607. self.app_cursor.enabled = False
  3608. try:
  3609. # App.log.debug('button=%d, x=%d, y=%d, xdata=%f, ydata=%f' % (
  3610. # event.button, event.pos[0], event.pos[1], self.pos[0], self.pos[1]))
  3611. modifiers = QtWidgets.QApplication.keyboardModifiers()
  3612. if event.button == 1:
  3613. # Reset here the relative coordinates so there is a new reference on the click position
  3614. if self.rel_point1 is None:
  3615. self.rel_point1 = self.pos
  3616. else:
  3617. self.rel_point2 = copy(self.rel_point1)
  3618. self.rel_point1 = self.pos
  3619. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  3620. if modifiers == QtCore.Qt.ShiftModifier:
  3621. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  3622. return
  3623. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will deselect,
  3624. # and if it's not selected then it will be selected
  3625. if modifiers == QtCore.Qt.ControlModifier:
  3626. # If there is no active command (self.command_active is None) then we check if we clicked on
  3627. # a object by checking the bounding limits against mouse click position
  3628. if self.command_active is None:
  3629. self.select_objects(key='CTRL')
  3630. else:
  3631. # If there is no active command (self.command_active is None) then we check if we clicked on a object by
  3632. # checking the bounding limits against mouse click position
  3633. if self.command_active is None:
  3634. self.select_objects()
  3635. self.on_mouse_move_over_plot(event, origin_click=True)
  3636. except Exception as e:
  3637. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  3638. def on_double_click_over_plot(self, event):
  3639. # make double click work only for the LMB
  3640. if event.button == 1:
  3641. if self.collection.get_selected():
  3642. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3643. # delete the selection shape(S) as it may be in the way
  3644. self.delete_selection_shape()
  3645. def on_mouse_move_over_plot(self, event, origin_click=None):
  3646. """
  3647. Callback for the mouse motion event over the plot. This event is generated
  3648. by the Matplotlib backend and has been registered in ``self.__init__()``.
  3649. For details, see: http://matplotlib.org/users/event_handling.html
  3650. :param event: Contains information about the event.
  3651. :param origin_click
  3652. :return: None
  3653. """
  3654. # So it can receive key presses
  3655. self.plotcanvas.vispy_canvas.native.setFocus()
  3656. self.pos_jump = event.pos
  3657. if origin_click is True:
  3658. pass
  3659. else:
  3660. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  3661. if event.button == 2:
  3662. self.panning_action = True
  3663. return
  3664. else:
  3665. self.panning_action = False
  3666. if self.rel_point1 is not None:
  3667. try: # May fail in case mouse not within axes
  3668. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3669. if self.grid_status():
  3670. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3671. self.app_cursor.enabled = True
  3672. # Update cursor
  3673. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  3674. else:
  3675. pos = (pos_canvas[0], pos_canvas[1])
  3676. self.app_cursor.enabled = False
  3677. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3678. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  3679. dx = pos[0] - self.rel_point1[0]
  3680. dy = pos[1] - self.rel_point1[1]
  3681. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3682. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3683. self.mouse = [pos[0], pos[1]]
  3684. # if the mouse is moved and the LMB is clicked then the action is a selection
  3685. if event.is_dragging == 1 and event.button == 1:
  3686. self.delete_selection_shape()
  3687. if dx < 0:
  3688. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  3689. face_color=self.defaults['global_alt_sel_fill'])
  3690. self.selection_type = False
  3691. else:
  3692. self.draw_moving_selection_shape(self.pos, pos)
  3693. self.selection_type = True
  3694. # delete the status message on mouse move
  3695. # self.inform.emit("")
  3696. except:
  3697. self.ui.position_label.setText("")
  3698. self.ui.rel_position_label.setText("")
  3699. self.mouse = None
  3700. def on_mouse_click_release_over_plot(self, event):
  3701. """
  3702. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  3703. and has been registered in ''self.__init__()''.
  3704. :param event: contains information about the event.
  3705. :return:
  3706. """
  3707. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3708. if self.grid_status():
  3709. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3710. else:
  3711. pos = (pos_canvas[0], pos_canvas[1])
  3712. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  3713. # canvas menu
  3714. try:
  3715. if event.button == 2: # right click
  3716. if self.panning_action is True:
  3717. self.panning_action = False
  3718. else:
  3719. self.cursor = QtGui.QCursor()
  3720. self.populate_cmenu_grids()
  3721. self.ui.popMenu.popup(self.cursor.pos())
  3722. except Exception as e:
  3723. log.warning("Error: %s" % str(e))
  3724. return
  3725. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  3726. # selection and then select a type of selection ("enclosing" or "touching")
  3727. try:
  3728. if event.button == 1: # left click
  3729. if self.selection_type is not None:
  3730. self.selection_area_handler(self.pos, pos, self.selection_type)
  3731. self.selection_type = None
  3732. except Exception as e:
  3733. log.warning("Error: %s" % str(e))
  3734. return
  3735. def selection_area_handler(self, start_pos, end_pos, sel_type):
  3736. """
  3737. :param start_pos: mouse position when the selection LMB click was done
  3738. :param end_pos: mouse position when the left mouse button is released
  3739. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  3740. :return:
  3741. """
  3742. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  3743. self.delete_selection_shape()
  3744. for obj in self.collection.get_list():
  3745. try:
  3746. # select the object(s) only if it is enabled (plotted)
  3747. if obj.options['plot']:
  3748. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']), (obj.options['xmax'], obj.options['ymin']),
  3749. (obj.options['xmax'], obj.options['ymax']), (obj.options['xmin'], obj.options['ymax'])])
  3750. if sel_type is True:
  3751. if poly_obj.within(poly_selection):
  3752. # create the selection box around the selected object
  3753. self.draw_selection_shape(obj)
  3754. self.collection.set_active(obj.options['name'])
  3755. else:
  3756. if poly_selection.intersects(poly_obj):
  3757. # create the selection box around the selected object
  3758. self.draw_selection_shape(obj)
  3759. self.collection.set_active(obj.options['name'])
  3760. except:
  3761. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  3762. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  3763. # In this case poly_obj creation (see above) will fail
  3764. pass
  3765. def select_objects(self, key=None):
  3766. # list where we store the overlapped objects under our mouse left click position
  3767. objects_under_the_click_list = []
  3768. # Populate the list with the overlapped objects on the click position
  3769. curr_x, curr_y = self.pos
  3770. for obj in self.all_objects_list:
  3771. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  3772. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  3773. if obj.options['name'] not in objects_under_the_click_list:
  3774. if obj.options['plot']:
  3775. # add objects to the objects_under_the_click list only if the object is plotted
  3776. # (active and not disabled)
  3777. objects_under_the_click_list.append(obj.options['name'])
  3778. try:
  3779. # If there is no element in the overlapped objects list then make everyone inactive
  3780. # because we selected "nothing"
  3781. if not objects_under_the_click_list:
  3782. self.collection.set_all_inactive()
  3783. # delete the possible selection box around a possible selected object
  3784. self.delete_selection_shape()
  3785. # and as a convenience move the focus to the Project tab because Selected tab is now empty
  3786. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  3787. # delete any text in the status bar, implicitly the last object name that was selected
  3788. self.inform.emit("")
  3789. else:
  3790. # case when there is only an object under the click and we toggle it
  3791. if len(objects_under_the_click_list) == 1:
  3792. if self.collection.get_active() is None :
  3793. self.collection.set_active(objects_under_the_click_list[0])
  3794. # create the selection box around the selected object
  3795. curr_sel_obj = self.collection.get_active()
  3796. self.draw_selection_shape(curr_sel_obj)
  3797. # self.inform.emit('[selected] %s: %s selected' %
  3798. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  3799. if curr_sel_obj.kind == 'gerber':
  3800. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3801. ('green', str(curr_sel_obj.options['name'])))
  3802. elif curr_sel_obj.kind == 'excellon':
  3803. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3804. ('brown', str(curr_sel_obj.options['name'])))
  3805. elif curr_sel_obj.kind == 'cncjob':
  3806. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3807. ('blue', str(curr_sel_obj.options['name'])))
  3808. elif curr_sel_obj.kind == 'geometry':
  3809. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3810. ('red', str(curr_sel_obj.options['name'])))
  3811. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  3812. self.collection.set_all_inactive()
  3813. self.delete_selection_shape()
  3814. self.collection.set_active(objects_under_the_click_list[0])
  3815. # create the selection box around the selected object
  3816. curr_sel_obj = self.collection.get_active()
  3817. self.draw_selection_shape(curr_sel_obj)
  3818. # self.inform.emit('[selected] %s: %s selected' %
  3819. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  3820. if curr_sel_obj.kind == 'gerber':
  3821. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3822. ('green', str(curr_sel_obj.options['name'])))
  3823. elif curr_sel_obj.kind == 'excellon':
  3824. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3825. ('brown', str(curr_sel_obj.options['name'])))
  3826. elif curr_sel_obj.kind == 'cncjob':
  3827. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3828. ('blue', str(curr_sel_obj.options['name'])))
  3829. elif curr_sel_obj.kind == 'geometry':
  3830. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3831. ('red', str(curr_sel_obj.options['name'])))
  3832. else:
  3833. self.collection.set_all_inactive()
  3834. self.delete_selection_shape()
  3835. self.inform.emit("")
  3836. else:
  3837. # If there is no selected object
  3838. # make active the first element of the overlapped objects list
  3839. if self.collection.get_active() is None:
  3840. self.collection.set_active(objects_under_the_click_list[0])
  3841. name_sel_obj = self.collection.get_active().options['name']
  3842. # In case that there is a selected object but it is not in the overlapped object list
  3843. # make that object inactive and activate the first element in the overlapped object list
  3844. if name_sel_obj not in objects_under_the_click_list:
  3845. self.collection.set_inactive(name_sel_obj)
  3846. name_sel_obj = objects_under_the_click_list[0]
  3847. self.collection.set_active(name_sel_obj)
  3848. else:
  3849. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  3850. self.collection.set_all_inactive()
  3851. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  3852. len(objects_under_the_click_list)])
  3853. curr_sel_obj = self.collection.get_active()
  3854. # delete the possible selection box around a possible selected object
  3855. self.delete_selection_shape()
  3856. # create the selection box around the selected object
  3857. self.draw_selection_shape(curr_sel_obj)
  3858. # self.inform.emit('[selected] %s: %s selected' %
  3859. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  3860. if curr_sel_obj.kind == 'gerber':
  3861. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3862. ('green', str(curr_sel_obj.options['name'])))
  3863. elif curr_sel_obj.kind == 'excellon':
  3864. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3865. ('brown', str(curr_sel_obj.options['name'])))
  3866. elif curr_sel_obj.kind == 'cncjob':
  3867. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3868. ('blue', str(curr_sel_obj.options['name'])))
  3869. elif curr_sel_obj.kind == 'geometry':
  3870. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3871. ('red', str(curr_sel_obj.options['name'])))
  3872. # for obj in self.collection.get_list():
  3873. # obj.plot()
  3874. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  3875. # TODO: on selected objects change the object colors and do not draw the selection box
  3876. # self.plotcanvas.vispy_canvas.update() # this updates the canvas
  3877. except Exception as e:
  3878. log.error("[ERROR] Something went bad. %s" % str(e))
  3879. return
  3880. def delete_selection_shape(self):
  3881. self.move_tool.sel_shapes.clear()
  3882. self.move_tool.sel_shapes.redraw()
  3883. def draw_selection_shape(self, sel_obj):
  3884. """
  3885. :param sel_obj: the object for which the selection shape must be drawn
  3886. :return:
  3887. """
  3888. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  3889. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  3890. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  3891. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  3892. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  3893. #blue_t = Color('blue')
  3894. blue_t = Color(self.defaults['global_sel_fill'])
  3895. blue_t.alpha = 0.3
  3896. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect, color=self.defaults['global_sel_line'],
  3897. face_color=blue_t, update=True, layer=0, tolerance=None))
  3898. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  3899. """
  3900. :param old_coords: old coordinates
  3901. :param coords: new coordinates
  3902. :return:
  3903. """
  3904. if 'color' in kwargs:
  3905. color = kwargs['color']
  3906. else:
  3907. color = self.defaults['global_sel_line']
  3908. if 'face_color' in kwargs:
  3909. face_color = kwargs['face_color']
  3910. else:
  3911. face_color = self.defaults['global_sel_fill']
  3912. x0, y0 = old_coords
  3913. x1, y1 = coords
  3914. pt1 = (x0, y0)
  3915. pt2 = (x1, y0)
  3916. pt3 = (x1, y1)
  3917. pt4 = (x0, y1)
  3918. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  3919. color_t = Color(face_color)
  3920. color_t.alpha = 0.3
  3921. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  3922. layer=0, tolerance=None)
  3923. def on_file_new_click(self):
  3924. if self.collection.get_list() and self.should_we_save:
  3925. msgbox = QtWidgets.QMessageBox()
  3926. # msgbox.setText("<B>Save changes ...</B>")
  3927. msgbox.setText("There are files/objects opened in FlatCAM.\n"
  3928. "Creating a New project will delete them.\n"
  3929. "Do you want to Save the project?")
  3930. msgbox.setWindowTitle("Save changes")
  3931. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3932. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel | QtWidgets.QMessageBox.Yes |
  3933. QtWidgets.QMessageBox.No)
  3934. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3935. response = msgbox.exec_()
  3936. if response == QtWidgets.QMessageBox.Yes:
  3937. self.on_file_saveprojectas()
  3938. elif response == QtWidgets.QMessageBox.Cancel:
  3939. return
  3940. self.on_file_new()
  3941. else:
  3942. self.on_file_new()
  3943. self.inform.emit("[success] New Project created...")
  3944. def on_file_new(self):
  3945. """
  3946. Callback for menu item File->New. Returns the application to its
  3947. startup state. This method is thread-safe.
  3948. :return: None
  3949. """
  3950. self.report_usage("on_file_new")
  3951. # Remove everything from memory
  3952. App.log.debug("on_file_new()")
  3953. # Clear pool
  3954. self.clear_pool()
  3955. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  3956. self.init_tcl()
  3957. self.delete_selection_shape()
  3958. self.collection.delete_all()
  3959. self.setup_component_editor()
  3960. # Clear project filename
  3961. self.project_filename = None
  3962. # Load the application defaults
  3963. self.load_defaults(filename='current_defaults')
  3964. # Re-fresh project options
  3965. self.on_options_app2project()
  3966. # Init Tools
  3967. self.init_tools()
  3968. # take the focus of the Notebook on Project Tab.
  3969. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  3970. def obj_properties(self):
  3971. self.report_usage("obj_properties()")
  3972. self.properties_tool.run()
  3973. def on_project_context_save(self):
  3974. obj = self.collection.get_active()
  3975. if type(obj) == FlatCAMGeometry:
  3976. self.on_file_exportdxf()
  3977. elif type(obj) == FlatCAMExcellon:
  3978. self.on_file_exportexcellon()
  3979. elif type(obj) == FlatCAMCNCjob:
  3980. obj.on_exportgcode_button_click()
  3981. elif type(obj) == FlatCAMGerber:
  3982. self.on_file_exportgerber()
  3983. def on_view_source(self):
  3984. try:
  3985. obj = self.collection.get_active()
  3986. except:
  3987. self.inform.emit("[WARNING_NOTCL] Select an Gerber or Excellon file to view it's source.")
  3988. # add the tab if it was closed
  3989. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, "Code Editor")
  3990. # first clear previous text in text editor (if any)
  3991. self.ui.code_editor.clear()
  3992. # Switch plot_area to CNCJob tab
  3993. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  3994. # then append the text from GCode to the text editor
  3995. file = StringIO(obj.source_file)
  3996. try:
  3997. for line in file:
  3998. proc_line = str(line).strip('\n')
  3999. self.ui.code_editor.append(proc_line)
  4000. except Exception as e:
  4001. log.debug('App.on_view_source() -->%s' % str(e))
  4002. self.inform.emit('[ERROR]App.on_view_source() -->%s' % str(e))
  4003. return
  4004. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  4005. self.handleTextChanged()
  4006. self.ui.show()
  4007. # if type(obj) == FlatCAMGerber:
  4008. # self.on_file_exportdxf()
  4009. # elif type(obj) == FlatCAMExcellon:
  4010. # self.on_file_exportexcellon()
  4011. def obj_move(self):
  4012. self.report_usage("obj_move()")
  4013. self.move_tool.run()
  4014. def on_fileopengerber(self):
  4015. """
  4016. File menu callback for opening a Gerber.
  4017. :return: None
  4018. """
  4019. self.report_usage("on_fileopengerber")
  4020. App.log.debug("on_fileopengerber()")
  4021. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *.gko " \
  4022. "*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  4023. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  4024. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  4025. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil);;" \
  4026. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  4027. "Allegro Files (*.art);;" \
  4028. "Mentor Files (*.pho *.gdo);;" \
  4029. "All Files (*.*)"
  4030. try:
  4031. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Gerber",
  4032. directory=self.get_last_folder(), filter=_filter_)
  4033. except TypeError:
  4034. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Gerber", filter=_filter_)
  4035. filenames = [str(filename) for filename in filenames]
  4036. if len(filenames) == 0:
  4037. self.inform.emit("[WARNING_NOTCL]Open Gerber cancelled.")
  4038. else:
  4039. for filename in filenames:
  4040. if filename != '':
  4041. self.worker_task.emit({'fcn': self.open_gerber,
  4042. 'params': [filename]})
  4043. def on_fileopenexcellon(self):
  4044. """
  4045. File menu callback for opening an Excellon file.
  4046. :return: None
  4047. """
  4048. self.report_usage("on_fileopenexcellon")
  4049. App.log.debug("on_fileopenexcellon()")
  4050. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc);;" \
  4051. "All Files (*.*)"
  4052. try:
  4053. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Excellon",
  4054. directory=self.get_last_folder(), filter=_filter_)
  4055. except TypeError:
  4056. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Excellon", filter=_filter_)
  4057. filenames = [str(filename) for filename in filenames]
  4058. if len(filenames) == 0:
  4059. self.inform.emit("[WARNING_NOTCL]Open Excellon cancelled.")
  4060. else:
  4061. for filename in filenames:
  4062. if filename != '':
  4063. self.worker_task.emit({'fcn': self.open_excellon,
  4064. 'params': [filename]})
  4065. def on_fileopengcode(self):
  4066. """
  4067. File menu call back for opening gcode.
  4068. :return: None
  4069. """
  4070. self.report_usage("on_fileopengcode")
  4071. App.log.debug("on_fileopengcode()")
  4072. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  4073. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  4074. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  4075. "All Files (*.*)"
  4076. try:
  4077. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open G-Code",
  4078. directory=self.get_last_folder(), filter=_filter_)
  4079. except TypeError:
  4080. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open G-Code", filter=_filter_)
  4081. filenames = [str(filename) for filename in filenames]
  4082. if len(filenames) == 0:
  4083. self.inform.emit("[WARNING_NOTCL]Open G-Code cancelled.")
  4084. else:
  4085. for filename in filenames:
  4086. if filename != '':
  4087. self.worker_task.emit({'fcn': self.open_gcode,
  4088. 'params': [filename]})
  4089. def on_file_openproject(self):
  4090. """
  4091. File menu callback for opening a project.
  4092. :return: None
  4093. """
  4094. self.report_usage("on_file_openproject")
  4095. App.log.debug("on_file_openproject()")
  4096. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  4097. try:
  4098. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Project",
  4099. directory=self.get_last_folder(), filter=_filter_)
  4100. except TypeError:
  4101. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Project", filter = _filter_)
  4102. # The Qt methods above will return a QString which can cause problems later.
  4103. # So far json.dump() will fail to serialize it.
  4104. # TODO: Improve the serialization methods and remove this fix.
  4105. filename = str(filename)
  4106. if filename == "":
  4107. self.inform.emit("[WARNING_NOTCL]Open Project cancelled.")
  4108. else:
  4109. # self.worker_task.emit({'fcn': self.open_project,
  4110. # 'params': [filename]})
  4111. # The above was failing because open_project() is not
  4112. # thread safe. The new_project()
  4113. self.open_project(filename)
  4114. def on_file_exportsvg(self):
  4115. """
  4116. Callback for menu item File->Export SVG.
  4117. :return: None
  4118. """
  4119. self.report_usage("on_file_exportsvg")
  4120. App.log.debug("on_file_exportsvg()")
  4121. obj = self.collection.get_active()
  4122. if obj is None:
  4123. self.inform.emit("WARNING: No object selected.")
  4124. msg = "Please Select a Geometry object to export"
  4125. msgbox = QtWidgets.QMessageBox()
  4126. msgbox.setInformativeText(msg)
  4127. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4128. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4129. msgbox.exec_()
  4130. return
  4131. # Check for more compatible types and add as required
  4132. if (not isinstance(obj, FlatCAMGeometry) and not isinstance(obj, FlatCAMGerber) and not isinstance(obj, FlatCAMCNCjob)
  4133. and not isinstance(obj, FlatCAMExcellon)):
  4134. msg = "[ERROR_NOTCL] Only Geometry, Gerber and CNCJob objects can be used."
  4135. msgbox = QtWidgets.QMessageBox()
  4136. msgbox.setInformativeText(msg)
  4137. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4138. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4139. msgbox.exec_()
  4140. return
  4141. name = self.collection.get_active().options["name"]
  4142. filter = "SVG File (*.svg);;All Files (*.*)"
  4143. try:
  4144. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4145. caption="Export SVG",
  4146. directory=self.get_last_save_folder() + '/' + str(name),
  4147. filter=filter)
  4148. except TypeError:
  4149. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export SVG", filter=filter)
  4150. filename = str(filename)
  4151. if filename == "":
  4152. self.inform.emit("[WARNING_NOTCL]Export SVG cancelled.")
  4153. return
  4154. else:
  4155. self.export_svg(name, filename)
  4156. self.file_saved.emit("SVG", filename)
  4157. def on_file_exportpng(self):
  4158. self.report_usage("on_file_exportpng")
  4159. App.log.debug("on_file_exportpng()")
  4160. image = _screenshot()
  4161. data = np.asarray(image)
  4162. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  4163. self.inform.emit('[[WARNING_NOTCL]] Data must be a 3D array with last dimension 3 or 4')
  4164. return
  4165. filter_ = "PNG File (*.png);;All Files (*.*)"
  4166. try:
  4167. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4168. caption="Export PNG Image",
  4169. directory=self.get_last_save_folder() + '/png_' + str(self.date).replace('-', ''),
  4170. filter=filter_)
  4171. except TypeError:
  4172. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export PNG Image", filter=filter_)
  4173. filename = str(filename)
  4174. if filename == "":
  4175. self.inform.emit("Export PNG cancelled.")
  4176. return
  4177. else:
  4178. write_png(filename, data)
  4179. self.file_saved.emit("png", filename)
  4180. def on_file_exportgerber(self):
  4181. """
  4182. Callback for menu item File->Export SVG.
  4183. :return: None
  4184. """
  4185. self.report_usage("on_file_exportgerber")
  4186. App.log.debug("on_file_exportgerber()")
  4187. obj = self.collection.get_active()
  4188. if obj is None:
  4189. self.inform.emit("[WARNING_NOTCL] No object selected. Please Select an Gerber object to export.")
  4190. return
  4191. # Check for more compatible types and add as required
  4192. if not isinstance(obj, FlatCAMGerber):
  4193. self.inform.emit("[ERROR_NOTCL] Failed. Only Gerber objects can be saved as Gerber files...")
  4194. return
  4195. name = self.collection.get_active().options["name"]
  4196. filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  4197. try:
  4198. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4199. caption="Export Gerber",
  4200. directory=self.get_last_save_folder() + '/' + name,
  4201. filter=filter)
  4202. except TypeError:
  4203. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export Gerber", filter=filter)
  4204. filename = str(filename)
  4205. if filename == "":
  4206. self.inform.emit("[WARNING_NOTCL]Export Gerber cancelled.")
  4207. return
  4208. else:
  4209. self.export_gerber(name, filename)
  4210. self.file_saved.emit("Gerber", filename)
  4211. def on_file_exportexcellon(self):
  4212. """
  4213. Callback for menu item File->Export SVG.
  4214. :return: None
  4215. """
  4216. self.report_usage("on_file_exportexcellon")
  4217. App.log.debug("on_file_exportexcellon()")
  4218. obj = self.collection.get_active()
  4219. if obj is None:
  4220. self.inform.emit("[WARNING_NOTCL] No object selected. Please Select an Excellon object to export.")
  4221. return
  4222. # Check for more compatible types and add as required
  4223. if not isinstance(obj, FlatCAMExcellon):
  4224. self.inform.emit("[ERROR_NOTCL] Failed. Only Excellon objects can be saved as Excellon files...")
  4225. return
  4226. name = self.collection.get_active().options["name"]
  4227. filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  4228. try:
  4229. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4230. caption="Export Excellon",
  4231. directory=self.get_last_save_folder() + '/' + name,
  4232. filter=filter)
  4233. except TypeError:
  4234. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export Excellon", filter=filter)
  4235. filename = str(filename)
  4236. if filename == "":
  4237. self.inform.emit("[WARNING_NOTCL]Export Excellon cancelled.")
  4238. return
  4239. else:
  4240. self.export_excellon(name, filename)
  4241. self.file_saved.emit("Excellon", filename)
  4242. def on_file_exportdxf(self):
  4243. """
  4244. Callback for menu item File->Export DXF.
  4245. :return: None
  4246. """
  4247. self.report_usage("on_file_exportdxf")
  4248. App.log.debug("on_file_exportdxf()")
  4249. obj = self.collection.get_active()
  4250. if obj is None:
  4251. self.inform.emit("W[WARNING_NOTCL] No object selected.")
  4252. msg = "Please Select a Geometry object to export"
  4253. msgbox = QtWidgets.QMessageBox()
  4254. msgbox.setInformativeText(msg)
  4255. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4256. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4257. msgbox.exec_()
  4258. return
  4259. # Check for more compatible types and add as required
  4260. if not isinstance(obj, FlatCAMGeometry):
  4261. msg = "[ERROR_NOTCL] Only Geometry objects can be used."
  4262. msgbox = QtWidgets.QMessageBox()
  4263. msgbox.setInformativeText(msg)
  4264. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4265. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4266. msgbox.exec_()
  4267. return
  4268. name = self.collection.get_active().options["name"]
  4269. filter = "DXF File (*.DXF);;All Files (*.*)"
  4270. try:
  4271. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4272. caption="Export DXF",
  4273. directory=self.get_last_save_folder() + '/' + name,
  4274. filter=filter)
  4275. except TypeError:
  4276. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export DXF", filter=filter)
  4277. filename = str(filename)
  4278. if filename == "":
  4279. self.inform.emit("[WARNING_NOTCL]Export DXF cancelled.")
  4280. return
  4281. else:
  4282. self.export_dxf(name, filename)
  4283. self.file_saved.emit("DXF", filename)
  4284. def on_file_importsvg(self, type_of_obj):
  4285. """
  4286. Callback for menu item File->Import SVG.
  4287. :param type_of_obj: to import the SVG as Geometry or as Gerber
  4288. :type type_of_obj: str
  4289. :return: None
  4290. """
  4291. self.report_usage("on_file_importsvg")
  4292. App.log.debug("on_file_importsvg()")
  4293. filter = "SVG File (*.svg);;All Files (*.*)"
  4294. try:
  4295. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import SVG",
  4296. directory=self.get_last_folder(), filter=filter)
  4297. except TypeError:
  4298. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import SVG", filter=filter)
  4299. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  4300. type_of_obj = "geometry"
  4301. filenames = [str(filename) for filename in filenames]
  4302. if len(filenames) == 0:
  4303. self.inform.emit("[WARNING_NOTCL]Open SVG cancelled.")
  4304. else:
  4305. for filename in filenames:
  4306. if filename != '':
  4307. self.worker_task.emit({'fcn': self.import_svg,
  4308. 'params': [filename, type_of_obj]})
  4309. def on_file_importdxf(self, type_of_obj):
  4310. """
  4311. Callback for menu item File->Import DXF.
  4312. :param type_of_obj: to import the DXF as Geometry or as Gerber
  4313. :type type_of_obj: str
  4314. :return: None
  4315. """
  4316. self.report_usage("on_file_importdxf")
  4317. App.log.debug("on_file_importdxf()")
  4318. filter = "DXF File (*.DXF);;All Files (*.*)"
  4319. try:
  4320. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import DXF",
  4321. directory=self.get_last_folder(), filter=filter)
  4322. except TypeError:
  4323. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import DXF", filter=filter)
  4324. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  4325. type_of_obj = "geometry"
  4326. filenames = [str(filename) for filename in filenames]
  4327. if len(filenames) == 0:
  4328. self.inform.emit("[WARNING_NOTCL]Open DXF cancelled.")
  4329. else:
  4330. for filename in filenames:
  4331. if filename != '':
  4332. self.worker_task.emit({'fcn': self.import_dxf,
  4333. 'params': [filename, type_of_obj]})
  4334. def on_filerunscript(self):
  4335. """
  4336. File menu callback for loading and running a TCL script.
  4337. :return: None
  4338. """
  4339. self.report_usage("on_filerunscript")
  4340. App.log.debug("on_file_runscript()")
  4341. _filter_ = "TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  4342. try:
  4343. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open TCL script",
  4344. directory=self.get_last_folder(), filter=_filter_)
  4345. except TypeError:
  4346. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open TCL script", filter=_filter_)
  4347. # The Qt methods above will return a QString which can cause problems later.
  4348. # So far json.dump() will fail to serialize it.
  4349. # TODO: Improve the serialization methods and remove this fix.
  4350. filename = str(filename)
  4351. if filename == "":
  4352. self.inform.emit("[WARNING_NOTCL]Open TCL script cancelled.")
  4353. else:
  4354. try:
  4355. with open(filename, "r") as tcl_script:
  4356. cmd_line_shellfile_content = tcl_script.read()
  4357. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  4358. except Exception as ext:
  4359. print("ERROR: ", ext)
  4360. sys.exit(2)
  4361. def on_file_saveproject(self):
  4362. """
  4363. Callback for menu item File->Save Project. Saves the project to
  4364. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  4365. if set to None. The project is saved by calling ``self.save_project()``.
  4366. :return: None
  4367. """
  4368. self.report_usage("on_file_saveproject")
  4369. if self.project_filename is None:
  4370. self.on_file_saveprojectas()
  4371. else:
  4372. self.worker_task.emit({'fcn': self.save_project,
  4373. 'params': [self.project_filename]})
  4374. # self.save_project(self.project_filename)
  4375. self.file_opened.emit("project", self.project_filename)
  4376. self.file_saved.emit("project", self.project_filename)
  4377. self.should_we_save = False
  4378. def on_file_saveprojectas(self, make_copy=False, thread=True):
  4379. """
  4380. Callback for menu item File->Save Project As... Opens a file
  4381. chooser and saves the project to the given file via
  4382. ``self.save_project()``.
  4383. :return: None
  4384. """
  4385. self.report_usage("on_file_saveprojectas")
  4386. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  4387. try:
  4388. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4389. caption="Save Project As ...",
  4390. directory=self.get_last_save_folder() + '/Project_' + self.date.replace('-', ''),
  4391. filter=filter_)
  4392. except TypeError:
  4393. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Save Project As ...", filter=filter_)
  4394. filename = str(filename)
  4395. if filename == '':
  4396. self.inform.emit("[WARNING_NOTCL]Save Project cancelled.")
  4397. return
  4398. try:
  4399. f = open(filename, 'r')
  4400. f.close()
  4401. exists = True
  4402. except IOError:
  4403. exists = False
  4404. # msg = "Project file exists. Overwrite?"
  4405. # if exists:
  4406. # msgbox = QtWidgets.QMessageBox()
  4407. # msgbox.setInformativeText(msg)
  4408. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel |QtWidgets.QMessageBox.Ok)
  4409. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Cancel)
  4410. # result = msgbox.exec_()
  4411. # if result ==QtWidgets.QMessageBox.Cancel:
  4412. # return
  4413. if thread is True:
  4414. self.worker_task.emit({'fcn': self.save_project,
  4415. 'params': [filename]})
  4416. else:
  4417. self.save_project(filename)
  4418. # self.save_project(filename)
  4419. self.file_opened.emit("project", filename)
  4420. self.file_saved.emit("project", filename)
  4421. if not make_copy:
  4422. self.project_filename = filename
  4423. self.should_we_save = False
  4424. def export_svg(self, obj_name, filename, scale_factor=0.00):
  4425. """
  4426. Exports a Geometry Object to an SVG file.
  4427. :param filename: Path to the SVG file to save to.
  4428. :return:
  4429. """
  4430. self.report_usage("export_svg()")
  4431. if filename is None:
  4432. filename = self.defaults["global_last_save_folder"]
  4433. self.log.debug("export_svg()")
  4434. try:
  4435. obj = self.collection.get_by_name(str(obj_name))
  4436. except:
  4437. # TODO: The return behavior has not been established... should raise exception?
  4438. return "Could not retrieve object: %s" % obj_name
  4439. with self.proc_container.new("Exporting SVG") as proc:
  4440. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4441. # Determine bounding area for svg export
  4442. bounds = obj.bounds()
  4443. size = obj.size()
  4444. # Convert everything to strings for use in the xml doc
  4445. svgwidth = str(size[0])
  4446. svgheight = str(size[1])
  4447. minx = str(bounds[0])
  4448. miny = str(bounds[1] - size[1])
  4449. uom = obj.units.lower()
  4450. # Add a SVG Header and footer to the svg output from shapely
  4451. # The transform flips the Y Axis so that everything renders
  4452. # properly within svg apps such as inkscape
  4453. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4454. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4455. svg_header += 'width="' + svgwidth + uom + '" '
  4456. svg_header += 'height="' + svgheight + uom + '" '
  4457. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  4458. svg_header += '<g transform="scale(1,-1)">'
  4459. svg_footer = '</g> </svg>'
  4460. svg_elem = svg_header + exported_svg + svg_footer
  4461. # Parse the xml through a xml parser just to add line feeds
  4462. # and to make it look more pretty for the output
  4463. svgcode = parse_xml_string(svg_elem)
  4464. with open(filename, 'w') as fp:
  4465. fp.write(svgcode.toprettyxml())
  4466. self.file_saved.emit("SVG", filename)
  4467. self.inform.emit("[success] SVG file exported to " + filename)
  4468. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  4469. """
  4470. Exports a Geometry Object to an SVG file in negative.
  4471. :param filename: Path to the SVG file to save to.
  4472. :param: use_thread: If True use threads
  4473. :type: Bool
  4474. :return:
  4475. """
  4476. self.report_usage("export_negative()")
  4477. if filename is None:
  4478. filename = self.defaults["global_last_save_folder"]
  4479. self.log.debug("export_svg() negative")
  4480. try:
  4481. obj = self.collection.get_by_name(str(obj_name))
  4482. except:
  4483. # TODO: The return behavior has not been established... should raise exception?
  4484. return "Could not retrieve object: %s" % obj_name
  4485. try:
  4486. box = self.collection.get_by_name(str(box_name))
  4487. except:
  4488. # TODO: The return behavior has not been established... should raise exception?
  4489. return "Could not retrieve object: %s" % box_name
  4490. if box is None:
  4491. self.inform.emit("[WARNING_NOTCL]No object Box. Using instead %s" % obj)
  4492. box = obj
  4493. def make_negative_film():
  4494. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4495. self.progress.emit(40)
  4496. # Determine bounding area for svg export
  4497. bounds = box.bounds()
  4498. size = box.size()
  4499. uom = obj.units.lower()
  4500. # Convert everything to strings for use in the xml doc
  4501. svgwidth = str(size[0] + (2 * boundary))
  4502. svgheight = str(size[1] + (2 * boundary))
  4503. minx = str(bounds[0] - boundary)
  4504. miny = str(bounds[1] + boundary + size[1])
  4505. miny_rect = str(bounds[1] - boundary)
  4506. # Add a SVG Header and footer to the svg output from shapely
  4507. # The transform flips the Y Axis so that everything renders
  4508. # properly within svg apps such as inkscape
  4509. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4510. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4511. svg_header += 'width="' + svgwidth + uom + '" '
  4512. svg_header += 'height="' + svgheight + uom + '" '
  4513. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  4514. svg_header += '>'
  4515. svg_header += '<g transform="scale(1,-1)">'
  4516. svg_footer = '</g> </svg>'
  4517. self.progress.emit(60)
  4518. # Change the attributes of the exported SVG
  4519. # We don't need stroke-width - wrong, we do when we have lines with certain width
  4520. # We set opacity to maximum
  4521. # We set the color to WHITE
  4522. root = ET.fromstring(exported_svg)
  4523. for child in root:
  4524. child.set('fill', '#FFFFFF')
  4525. child.set('opacity', '1.0')
  4526. child.set('stroke', '#FFFFFF')
  4527. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  4528. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  4529. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  4530. first_svg_elem_tag = 'rect'
  4531. first_svg_elem_attribs = {
  4532. 'x': minx,
  4533. 'y': miny_rect,
  4534. 'width': svgwidth,
  4535. 'height': svgheight,
  4536. 'id': 'neg_rect',
  4537. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  4538. }
  4539. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  4540. exported_svg = ET.tostring(root)
  4541. svg_elem = svg_header + str(exported_svg) + svg_footer
  4542. self.progress.emit(80)
  4543. # Parse the xml through a xml parser just to add line feeds
  4544. # and to make it look more pretty for the output
  4545. doc = parse_xml_string(svg_elem)
  4546. with open(filename, 'w') as fp:
  4547. fp.write(doc.toprettyxml())
  4548. self.progress.emit(100)
  4549. self.file_saved.emit("SVG", filename)
  4550. self.inform.emit("[success] SVG file exported to " + filename)
  4551. if use_thread is True:
  4552. proc = self.proc_container.new("Generating Film ... Please wait.")
  4553. def job_thread_film(app_obj):
  4554. try:
  4555. make_negative_film()
  4556. except Exception as e:
  4557. proc.done()
  4558. return
  4559. proc.done()
  4560. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  4561. else:
  4562. make_negative_film()
  4563. def export_svg_black(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  4564. """
  4565. Exports a Geometry Object to an SVG file in negative.
  4566. :param filename: Path to the SVG file to save to.
  4567. :param: use_thread: If True use threads
  4568. :type: Bool
  4569. :return:
  4570. """
  4571. self.report_usage("export_svg_black()")
  4572. if filename is None:
  4573. filename = self.defaults["global_last_save_folder"]
  4574. self.log.debug("export_svg() black")
  4575. try:
  4576. obj = self.collection.get_by_name(str(obj_name))
  4577. except:
  4578. # TODO: The return behavior has not been established... should raise exception?
  4579. return "Could not retrieve object: %s" % obj_name
  4580. try:
  4581. box = self.collection.get_by_name(str(box_name))
  4582. except:
  4583. # TODO: The return behavior has not been established... should raise exception?
  4584. return "Could not retrieve object: %s" % box_name
  4585. if box is None:
  4586. self.inform.emit("[WARNING_NOTCL]No object Box. Using instead %s" % obj)
  4587. box = obj
  4588. def make_black_film():
  4589. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4590. self.progress.emit(40)
  4591. # Change the attributes of the exported SVG
  4592. # We don't need stroke-width
  4593. # We set opacity to maximum
  4594. # We set the colour to WHITE
  4595. root = ET.fromstring(exported_svg)
  4596. for child in root:
  4597. child.set('fill', '#000000')
  4598. child.set('opacity', '1.0')
  4599. child.set('stroke', '#000000')
  4600. exported_svg = ET.tostring(root)
  4601. # Determine bounding area for svg export
  4602. bounds = box.bounds()
  4603. size = box.size()
  4604. # This contain the measure units
  4605. uom = obj.units.lower()
  4606. # Define a boundary around SVG of about 1.0mm (~39mils)
  4607. if uom in "mm":
  4608. boundary = 1.0
  4609. else:
  4610. boundary = 0.0393701
  4611. self.progress.emit(80)
  4612. # Convert everything to strings for use in the xml doc
  4613. svgwidth = str(size[0] + (2 * boundary))
  4614. svgheight = str(size[1] + (2 * boundary))
  4615. minx = str(bounds[0] - boundary)
  4616. miny = str(bounds[1] + boundary + size[1])
  4617. self.log.debug(minx)
  4618. self.log.debug(miny)
  4619. # Add a SVG Header and footer to the svg output from shapely
  4620. # The transform flips the Y Axis so that everything renders
  4621. # properly within svg apps such as inkscape
  4622. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4623. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4624. svg_header += 'width="' + svgwidth + uom + '" '
  4625. svg_header += 'height="' + svgheight + uom + '" '
  4626. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  4627. svg_header += '>'
  4628. svg_header += '<g transform="scale(1,-1)">'
  4629. svg_footer = '</g> </svg>'
  4630. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  4631. self.progress.emit(90)
  4632. # Parse the xml through a xml parser just to add line feeds
  4633. # and to make it look more pretty for the output
  4634. doc = parse_xml_string(svg_elem)
  4635. with open(filename, 'w') as fp:
  4636. fp.write(doc.toprettyxml())
  4637. self.progress.emit(100)
  4638. self.file_saved.emit("SVG", filename)
  4639. self.inform.emit("[success] SVG file exported to " + filename)
  4640. if use_thread is True:
  4641. proc = self.proc_container.new("Generating Film ... Please wait.")
  4642. def job_thread_film(app_obj):
  4643. try:
  4644. make_black_film()
  4645. except Exception as e:
  4646. proc.done()
  4647. return
  4648. proc.done()
  4649. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  4650. else:
  4651. make_black_film()
  4652. def export_gerber(self, obj_name, filename, use_thread=True):
  4653. """
  4654. Exports a Gerber Object to an Gerber file.
  4655. :param filename: Path to the Gerber file to save to.
  4656. :return:
  4657. """
  4658. self.report_usage("export_gerber()")
  4659. if filename is None:
  4660. filename = self.defaults["global_last_save_folder"]
  4661. self.log.debug("export_gerber()")
  4662. obj = self.collection.get_by_name(obj_name)
  4663. file_string = StringIO(obj.source_file)
  4664. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  4665. with open(filename, 'w') as file:
  4666. file.writelines('G04*\n')
  4667. file.writelines('G04 GERBER (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  4668. (str(self.version), str(self.version_date)))
  4669. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  4670. file.writelines('G04 Created on : %s*\n' % time_string)
  4671. for line in file_string:
  4672. file.writelines(line)
  4673. def export_excellon(self, obj_name, filename, use_thread=True):
  4674. """
  4675. Exports a Excellon Object to an Excellon file.
  4676. :param filename: Path to the Excellon file to save to.
  4677. :return:
  4678. """
  4679. self.report_usage("export_excellon()")
  4680. if filename is None:
  4681. filename = self.defaults["global_last_save_folder"]
  4682. self.log.debug("export_excellon()")
  4683. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  4684. self.defaults["excellon_exp_decimals"]
  4685. )
  4686. units = ''
  4687. try:
  4688. obj = self.collection.get_by_name(str(obj_name))
  4689. except:
  4690. # TODO: The return behavior has not been established... should raise exception?
  4691. return "Could not retrieve object: %s" % obj_name
  4692. # updated units
  4693. eunits = self.defaults["excellon_exp_units"]
  4694. ewhole = self.defaults["excellon_exp_integer"]
  4695. efract = self.defaults["excellon_exp_decimals"]
  4696. ezeros = self.defaults["excellon_exp_zeros"]
  4697. eformat = self.defaults[ "excellon_exp_format"]
  4698. fc_units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4699. if fc_units == 'MM':
  4700. factor = 1 if eunits == 'METRIC' else 0.03937
  4701. else:
  4702. factor = 25.4 if eunits == 'METRIC' else 1
  4703. def make_excellon():
  4704. try:
  4705. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  4706. header = 'M48\n'
  4707. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  4708. (str(self.version), str(self.version_date))
  4709. header += ';Filename: %s' % str(obj_name) + '\n'
  4710. header += ';Created on : %s' % time_str + '\n'
  4711. if eformat == 'dec':
  4712. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor)
  4713. header += eunits + '\n'
  4714. for tool in obj.tools:
  4715. if eunits == 'METRIC':
  4716. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  4717. tool=str(tool),
  4718. dec=2)
  4719. else:
  4720. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  4721. tool=str(tool),
  4722. dec=4)
  4723. else:
  4724. if ezeros == 'LZ':
  4725. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  4726. form='ndec', e_zeros='LZ', factor=factor)
  4727. header += '%s,%s\n' % (eunits, 'LZ')
  4728. header += format_exc
  4729. for tool in obj.tools:
  4730. if eunits == 'METRIC':
  4731. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  4732. tool=str(tool),
  4733. dec=2)
  4734. else:
  4735. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  4736. tool=str(tool),
  4737. dec=4)
  4738. else:
  4739. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  4740. form='ndec', e_zeros='TZ', factor=factor)
  4741. header += '%s,%s\n' % (eunits, 'TZ')
  4742. header += format_exc
  4743. for tool in obj.tools:
  4744. if eunits == 'METRIC':
  4745. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  4746. tool=str(tool),
  4747. dec=2)
  4748. else:
  4749. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  4750. tool=str(tool),
  4751. dec=4)
  4752. header += '%\n'
  4753. footer = 'M30\n'
  4754. exported_excellon = header
  4755. exported_excellon += excellon_code
  4756. exported_excellon += footer
  4757. with open(filename, 'w') as fp:
  4758. fp.write(exported_excellon)
  4759. self.file_saved.emit("Excellon", filename)
  4760. self.inform.emit("[success] Excellon file exported to " + filename)
  4761. except Exception as e:
  4762. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  4763. return 'fail'
  4764. if use_thread is True:
  4765. with self.proc_container.new("Exporting Excellon") as proc:
  4766. def job_thread_exc(app_obj):
  4767. ret = make_excellon()
  4768. if ret == 'fail':
  4769. self.inform.emit('[ERROR_NOTCL] Could not export Excellon file.')
  4770. return
  4771. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  4772. else:
  4773. ret = make_excellon()
  4774. if ret == 'fail':
  4775. self.inform.emit('[ERROR_NOTCL] Could not export Excellon file.')
  4776. return
  4777. def export_dxf(self, obj_name, filename, use_thread=True):
  4778. """
  4779. Exports a Geometry Object to an DXF file.
  4780. :param filename: Path to the DXF file to save to.
  4781. :return:
  4782. """
  4783. self.report_usage("export_dxf()")
  4784. if filename is None:
  4785. filename = self.defaults["global_last_save_folder"]
  4786. self.log.debug("export_dxf()")
  4787. format_exc = ''
  4788. units = ''
  4789. try:
  4790. obj = self.collection.get_by_name(str(obj_name))
  4791. except:
  4792. # TODO: The return behavior has not been established... should raise exception?
  4793. return "Could not retrieve object: %s" % obj_name
  4794. # updated units
  4795. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4796. if units == 'IN' or units == 'INCH':
  4797. units = 'INCH'
  4798. elif units == 'MM' or units == 'METIRC':
  4799. units ='METRIC'
  4800. def make_dxf():
  4801. try:
  4802. dxf_code = obj.export_dxf()
  4803. dxf_code.saveas(filename)
  4804. self.file_saved.emit("DXF", filename)
  4805. self.inform.emit("[success] DXF file exported to " + filename)
  4806. except:
  4807. return 'fail'
  4808. if use_thread is True:
  4809. with self.proc_container.new("Exporting DXF") as proc:
  4810. def job_thread_exc(app_obj):
  4811. ret = make_dxf()
  4812. if ret == 'fail':
  4813. self.inform.emit('[[WARNING_NOTCL]] Could not export DXF file.')
  4814. return
  4815. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  4816. else:
  4817. ret = make_dxf()
  4818. if ret == 'fail':
  4819. self.inform.emit('[[WARNING_NOTCL]] Could not export DXF file.')
  4820. return
  4821. def import_svg(self, filename, geo_type='geometry', outname=None):
  4822. """
  4823. Adds a new Geometry Object to the projects and populates
  4824. it with shapes extracted from the SVG file.
  4825. :param filename: Path to the SVG file.
  4826. :param outname:
  4827. :return:
  4828. """
  4829. self.report_usage("import_svg()")
  4830. obj_type = ""
  4831. if geo_type is None or geo_type == "geometry":
  4832. obj_type = "geometry"
  4833. elif geo_type == "gerber":
  4834. obj_type = geo_type
  4835. else:
  4836. self.inform.emit("[ERROR_NOTCL] Not supported type was choosed as parameter. "
  4837. "Only Geometry and Gerber are supported")
  4838. return
  4839. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4840. def obj_init(geo_obj, app_obj):
  4841. geo_obj.import_svg(filename, obj_type, units=units)
  4842. geo_obj.multigeo = False
  4843. with self.proc_container.new("Importing SVG") as proc:
  4844. # Object name
  4845. name = outname or filename.split('/')[-1].split('\\')[-1]
  4846. self.new_object(obj_type, name, obj_init, autoselected=False)
  4847. self.progress.emit(20)
  4848. # Register recent file
  4849. self.file_opened.emit("svg", filename)
  4850. # GUI feedback
  4851. self.inform.emit("[success] Opened: " + filename)
  4852. self.progress.emit(100)
  4853. def import_dxf(self, filename, geo_type='geometry', outname=None):
  4854. """
  4855. Adds a new Geometry Object to the projects and populates
  4856. it with shapes extracted from the DXF file.
  4857. :param filename: Path to the DXF file.
  4858. :param outname:
  4859. :type putname: str
  4860. :return:
  4861. """
  4862. self.report_usage("import_dxf()")
  4863. obj_type = ""
  4864. if geo_type is None or geo_type == "geometry":
  4865. obj_type = "geometry"
  4866. elif geo_type == "gerber":
  4867. obj_type = geo_type
  4868. else:
  4869. self.inform.emit("[ERROR_NOTCL] Not supported type was choosed as parameter. "
  4870. "Only Geometry and Gerber are supported")
  4871. return
  4872. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4873. def obj_init(geo_obj, app_obj):
  4874. geo_obj.import_dxf(filename, obj_type, units=units)
  4875. geo_obj.multigeo = False
  4876. with self.proc_container.new("Importing DXF") as proc:
  4877. # Object name
  4878. name = outname or filename.split('/')[-1].split('\\')[-1]
  4879. self.new_object(obj_type, name, obj_init, autoselected=False)
  4880. self.progress.emit(20)
  4881. # Register recent file
  4882. self.file_opened.emit("dxf", filename)
  4883. # GUI feedback
  4884. self.inform.emit("[success] Opened: " + filename)
  4885. self.progress.emit(100)
  4886. def import_image(self, filename, type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  4887. """
  4888. Adds a new Geometry Object to the projects and populates
  4889. it with shapes extracted from the SVG file.
  4890. :param filename: Path to the SVG file.
  4891. :param outname:
  4892. :return:
  4893. """
  4894. self.report_usage("import_image()")
  4895. obj_type = ""
  4896. if type is None or type == "geometry":
  4897. obj_type = "geometry"
  4898. elif type == "gerber":
  4899. obj_type = type
  4900. else:
  4901. self.inform.emit("[ERROR_NOTCL] Not supported type was picked as parameter. "
  4902. "Only Geometry and Gerber are supported")
  4903. return
  4904. def obj_init(geo_obj, app_obj):
  4905. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  4906. geo_obj.multigeo = False
  4907. with self.proc_container.new("Importing Image") as proc:
  4908. # Object name
  4909. name = outname or filename.split('/')[-1].split('\\')[-1]
  4910. units = self.general_options_form.general_app_group.units_radio.get_value()
  4911. self.new_object(obj_type, name, obj_init)
  4912. self.progress.emit(20)
  4913. # Register recent file
  4914. self.file_opened.emit("image", filename)
  4915. # GUI feedback
  4916. self.inform.emit("[success] Opened: " + filename)
  4917. self.progress.emit(100)
  4918. def open_gerber(self, filename, outname=None):
  4919. """
  4920. Opens a Gerber file, parses it and creates a new object for
  4921. it in the program. Thread-safe.
  4922. :param outname: Name of the resulting object. None causes the
  4923. name to be that of the file.
  4924. :param filename: Gerber file filename
  4925. :type filename: str
  4926. :param follow: If true, the parser will not create polygons, just lines
  4927. following the gerber path.
  4928. :type follow: bool
  4929. :return: None
  4930. """
  4931. # How the object should be initialized
  4932. def obj_init(gerber_obj, app_obj):
  4933. assert isinstance(gerber_obj, FlatCAMGerber), \
  4934. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  4935. # Opening the file happens here
  4936. self.progress.emit(30)
  4937. try:
  4938. gerber_obj.parse_file(filename)
  4939. except IOError:
  4940. app_obj.inform.emit("[ERROR_NOTCL] Failed to open file: " + filename)
  4941. app_obj.progress.emit(0)
  4942. self.inform.emit('[ERROR_NOTCL] Failed to open file: ' + filename)
  4943. return "fail"
  4944. except ParseError as err:
  4945. app_obj.inform.emit("[ERROR_NOTCL] Failed to parse file: " + filename + ". " + str(err))
  4946. app_obj.progress.emit(0)
  4947. self.log.error(str(err))
  4948. return "fail"
  4949. except:
  4950. msg = "[ERROR] An internal error has ocurred. See shell.\n"
  4951. msg += traceback.format_exc()
  4952. app_obj.inform.emit(msg)
  4953. return "fail"
  4954. if gerber_obj.is_empty():
  4955. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  4956. # self.collection.set_active(gerber_obj.options["name"])
  4957. # self.collection.delete_active()
  4958. self.inform.emit("[ERROR_NOTCL] Object is not Gerber file or empty. Aborting object creation.")
  4959. return "fail"
  4960. # Further parsing
  4961. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  4962. App.log.debug("open_gerber()")
  4963. with self.proc_container.new("Opening Gerber") as proc:
  4964. self.progress.emit(10)
  4965. # Object name
  4966. name = outname or filename.split('/')[-1].split('\\')[-1]
  4967. ### Object creation ###
  4968. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  4969. if ret == 'fail':
  4970. self.inform.emit('[ERROR_NOTCL] Open Gerber failed. Probable not a Gerber file.')
  4971. return
  4972. # Register recent file
  4973. self.file_opened.emit("gerber", filename)
  4974. self.progress.emit(100)
  4975. # GUI feedback
  4976. self.inform.emit("[success] Opened: " + filename)
  4977. def open_excellon(self, filename, outname=None):
  4978. """
  4979. Opens an Excellon file, parses it and creates a new object for
  4980. it in the program. Thread-safe.
  4981. :param outname: Name of the resulting object. None causes the
  4982. name to be that of the file.
  4983. :param filename: Excellon file filename
  4984. :type filename: str
  4985. :return: None
  4986. """
  4987. App.log.debug("open_excellon()")
  4988. #self.progress.emit(10)
  4989. # How the object should be initialized
  4990. def obj_init(excellon_obj, app_obj):
  4991. # self.progress.emit(20)
  4992. try:
  4993. ret = excellon_obj.parse_file(filename)
  4994. if ret == "fail":
  4995. log.debug("Excellon parsing failed.")
  4996. self.inform.emit("[ERROR_NOTCL] This is not Excellon file.")
  4997. return "fail"
  4998. except IOError:
  4999. app_obj.inform.emit("[ERROR_NOTCL] Cannot open file: " + filename)
  5000. log.debug("Could not open Excellon object.")
  5001. self.progress.emit(0) # TODO: self and app_bjj mixed
  5002. return "fail"
  5003. except:
  5004. msg = "[ERROR_NOTCL] An internal error has occurred. See shell.\n"
  5005. msg += traceback.format_exc()
  5006. app_obj.inform.emit(msg)
  5007. return "fail"
  5008. ret = excellon_obj.create_geometry()
  5009. if ret == 'fail':
  5010. log.debug("Could not create geometry for Excellon object.")
  5011. return "fail"
  5012. # if excellon_obj.is_empty():
  5013. # app_obj.inform.emit("[ERROR_NOTCL] No geometry found in file: " + filename)
  5014. # return "fail"
  5015. for tool in excellon_obj.tools:
  5016. if excellon_obj.tools[tool]['solid_geometry']:
  5017. return
  5018. app_obj.inform.emit("[ERROR_NOTCL] No geometry found in file: " + filename)
  5019. return "fail"
  5020. with self.proc_container.new("Opening Excellon."):
  5021. # Object name
  5022. name = outname or filename.split('/')[-1].split('\\')[-1]
  5023. ret = self.new_object("excellon", name, obj_init, autoselected=False)
  5024. if ret == 'fail':
  5025. self.inform.emit('[ERROR_NOTCL] Open Excellon file failed. Probable not an Excellon file.')
  5026. return
  5027. # Register recent file
  5028. self.file_opened.emit("excellon", filename)
  5029. # GUI feedback
  5030. self.inform.emit("[success] Opened: " + filename)
  5031. # self.progress.emit(100)
  5032. def open_gcode(self, filename, outname=None):
  5033. """
  5034. Opens a G-gcode file, parses it and creates a new object for
  5035. it in the program. Thread-safe.
  5036. :param outname: Name of the resulting object. None causes the
  5037. name to be that of the file.
  5038. :param filename: G-code file filename
  5039. :type filename: str
  5040. :return: None
  5041. """
  5042. App.log.debug("open_gcode()")
  5043. # How the object should be initialized
  5044. def obj_init(job_obj, app_obj_):
  5045. """
  5046. :type app_obj_: App
  5047. """
  5048. assert isinstance(app_obj_, App), \
  5049. "Initializer expected App, got %s" % type(app_obj_)
  5050. self.progress.emit(10)
  5051. try:
  5052. f = open(filename)
  5053. gcode = f.read()
  5054. f.close()
  5055. except IOError:
  5056. app_obj_.inform.emit("[ERROR_NOTCL] Failed to open " + filename)
  5057. self.progress.emit(0)
  5058. return "fail"
  5059. job_obj.gcode = gcode
  5060. self.progress.emit(20)
  5061. ret = job_obj.gcode_parse()
  5062. if ret == "fail":
  5063. self.inform.emit("[ERROR_NOTCL] This is not GCODE")
  5064. return "fail"
  5065. self.progress.emit(60)
  5066. job_obj.create_geometry()
  5067. with self.proc_container.new("Opening G-Code."):
  5068. # Object name
  5069. name = outname or filename.split('/')[-1].split('\\')[-1]
  5070. # New object creation and file processing
  5071. ret = self.new_object("cncjob", name, obj_init, autoselected=False)
  5072. if ret == 'fail':
  5073. self.inform.emit("[ERROR_NOTCL] Failed to create CNCJob Object. Probable not a GCode file.\n "
  5074. "Attempting to create a FlatCAM CNCJob Object from "
  5075. "G-Code file failed during processing")
  5076. return "fail"
  5077. # Register recent file
  5078. self.file_opened.emit("cncjob", filename)
  5079. # GUI feedback
  5080. self.inform.emit("[success] Opened: " + filename)
  5081. self.progress.emit(100)
  5082. def open_project(self, filename, run_from_arg=None):
  5083. """
  5084. Loads a project from the specified file.
  5085. 1) Loads and parses file
  5086. 2) Registers the file as recently opened.
  5087. 3) Calls on_file_new()
  5088. 4) Updates options
  5089. 5) Calls new_object() with the object's from_dict() as init method.
  5090. 6) Calls plot_all()
  5091. :param filename: Name of the file from which to load.
  5092. :type filename: str
  5093. :return: None
  5094. """
  5095. App.log.debug("Opening project: " + filename)
  5096. # Open and parse an uncompressed Project file
  5097. try:
  5098. f = open(filename, 'r')
  5099. except IOError:
  5100. App.log.error("Failed to open project file: %s" % filename)
  5101. self.inform.emit("[ERROR_NOTCL] Failed to open project file: %s" % filename)
  5102. return
  5103. try:
  5104. d = json.load(f, object_hook=dict2obj)
  5105. except:
  5106. App.log.error("Failed to parse project file: %s" % filename)
  5107. self.inform.emit("[ERROR_NOTCL] Failed to parse project file: %s" % filename)
  5108. f.close()
  5109. # Open and parse a compressed Project file
  5110. try:
  5111. with lzma.open(filename) as f:
  5112. file_content = f.read().decode('utf-8')
  5113. d = json.loads(file_content, object_hook=dict2obj)
  5114. except IOError:
  5115. App.log.error("Failed to open project file: %s" % filename)
  5116. self.inform.emit("[ERROR_NOTCL] Failed to open project file: %s" % filename)
  5117. return
  5118. self.file_opened.emit("project", filename)
  5119. # Clear the current project
  5120. ## NOT THREAD SAFE ##
  5121. if run_from_arg is True:
  5122. pass
  5123. else:
  5124. self.on_file_new()
  5125. #Project options
  5126. self.options.update(d['options'])
  5127. self.project_filename = filename
  5128. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  5129. self.set_screen_units(self.options["units"])
  5130. # Re create objects
  5131. App.log.debug("Re-creating objects...")
  5132. for obj in d['objs']:
  5133. def obj_init(obj_inst, app_inst):
  5134. obj_inst.from_dict(obj)
  5135. App.log.debug(obj['kind'] + ": " + obj['options']['name'])
  5136. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=True)
  5137. self.plot_all()
  5138. self.inform.emit("[success] Project loaded from: " + filename)
  5139. self.should_we_save = False
  5140. App.log.debug("Project loaded")
  5141. def propagate_defaults(self, silent=False):
  5142. """
  5143. This method is used to set default values in classes. It's
  5144. an alternative to project options but allows the use
  5145. of values invisible to the user.
  5146. :return: None
  5147. """
  5148. if silent is False:
  5149. self.log.debug("propagate_defaults()")
  5150. # Which objects to update the given parameters.
  5151. routes = {
  5152. "global_zdownrate": CNCjob,
  5153. "excellon_zeros": Excellon,
  5154. "excellon_format_upper_in": Excellon,
  5155. "excellon_format_lower_in": Excellon,
  5156. "excellon_format_upper_mm": Excellon,
  5157. "excellon_format_lower_mm": Excellon,
  5158. "excellon_units": Excellon,
  5159. "gerber_use_buffer_for_union": Gerber,
  5160. "geometry_multidepth": Geometry
  5161. }
  5162. for param in routes:
  5163. if param in routes[param].defaults:
  5164. try:
  5165. routes[param].defaults[param] = self.defaults[param]
  5166. if silent is False:
  5167. self.log.debug(" " + param + " OK")
  5168. except KeyError:
  5169. if silent is False:
  5170. self.log.debug(" ERROR: " + param + " not in defaults.")
  5171. else:
  5172. # Try extracting the name:
  5173. # classname_param here is param in the object
  5174. if param.find(routes[param].__name__.lower() + "_") == 0:
  5175. p = param[len(routes[param].__name__) + 1:]
  5176. if p in routes[param].defaults:
  5177. routes[param].defaults[p] = self.defaults[param]
  5178. if silent is False:
  5179. self.log.debug(" " + param + " OK!")
  5180. def restore_main_win_geom(self):
  5181. try:
  5182. self.ui.setGeometry(self.defaults["global_def_win_x"],
  5183. self.defaults["global_def_win_y"],
  5184. self.defaults["global_def_win_w"],
  5185. self.defaults["global_def_win_h"])
  5186. self.ui.splitter.setSizes([self.defaults["def_notebook_width"], 0])
  5187. settings = QSettings("Open Source", "FlatCAM")
  5188. if settings.contains("maximized_gui"):
  5189. maximized_ui = settings.value('maximized_gui', type=bool)
  5190. if maximized_ui is True:
  5191. self.ui.showMaximized()
  5192. except KeyError:
  5193. pass
  5194. def plot_all(self, zoom=True):
  5195. """
  5196. Re-generates all plots from all objects.
  5197. :return: None
  5198. """
  5199. self.log.debug("Plot_all()")
  5200. for obj in self.collection.get_list():
  5201. def worker_task(obj):
  5202. with self.proc_container.new("Plotting"):
  5203. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  5204. if zoom:
  5205. self.object_plotted.emit(obj)
  5206. # Send to worker
  5207. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  5208. # self.progress.emit(10)
  5209. #
  5210. # def worker_task(app_obj):
  5211. # print "worker task"
  5212. # percentage = 0.1
  5213. # try:
  5214. # delta = 0.9 / len(self.collection.get_list())
  5215. # except ZeroDivisionError:
  5216. # self.progress.emit(0)
  5217. # return
  5218. # for obj in self.collection.get_list():
  5219. # with self.proc_container.new("Plotting"):
  5220. # obj.plot()
  5221. # app_obj.object_plotted.emit(obj)
  5222. #
  5223. # percentage += delta
  5224. # self.progress.emit(int(percentage*100))
  5225. #
  5226. # self.progress.emit(0)
  5227. # self.plots_updated.emit()
  5228. #
  5229. # # Send to worker
  5230. # #self.worker.add_task(worker_task, [self])
  5231. # self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  5232. def register_folder(self, filename):
  5233. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  5234. def register_save_folder(self, filename):
  5235. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  5236. def set_progress_bar(self, percentage, text=""):
  5237. self.ui.progress_bar.setValue(int(percentage))
  5238. def setup_shell(self):
  5239. """
  5240. Creates shell functions. Runs once at startup.
  5241. :return: None
  5242. """
  5243. self.log.debug("setup_shell()")
  5244. def shelp(p=None):
  5245. if not p:
  5246. return "Available commands:\n" + \
  5247. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  5248. "\n\nType help <command_name> for usage.\n Example: help open_gerber"
  5249. if p not in commands:
  5250. return "Unknown command: %s" % p
  5251. return commands[p]["help"]
  5252. # --- Migrated to new architecture ---
  5253. # def options(name):
  5254. # ops = self.collection.get_by_name(str(name)).options
  5255. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  5256. def h(*args):
  5257. """
  5258. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  5259. and standalone parameters into list.
  5260. """
  5261. kwa = {}
  5262. a = []
  5263. n = len(args)
  5264. name = None
  5265. for i in range(n):
  5266. match = re.search(r'^-([a-zA-Z].*)', args[i])
  5267. if match:
  5268. assert name is None
  5269. name = match.group(1)
  5270. continue
  5271. if name is None:
  5272. a.append(args[i])
  5273. else:
  5274. kwa[name] = args[i]
  5275. name = None
  5276. return a, kwa
  5277. @contextmanager
  5278. def wait_signal(signal, timeout=10000):
  5279. """
  5280. Block loop until signal emitted, timeout (ms) elapses
  5281. or unhandled exception happens in a thread.
  5282. :param signal: Signal to wait for.
  5283. """
  5284. loop = QtCore.QEventLoop()
  5285. # Normal termination
  5286. signal.connect(loop.quit)
  5287. # Termination by exception in thread
  5288. self.thread_exception.connect(loop.quit)
  5289. status = {'timed_out': False}
  5290. def report_quit():
  5291. status['timed_out'] = True
  5292. loop.quit()
  5293. yield
  5294. # Temporarily change how exceptions are managed.
  5295. oeh = sys.excepthook
  5296. ex = []
  5297. def except_hook(type_, value, traceback_):
  5298. ex.append(value)
  5299. oeh(type_, value, traceback_)
  5300. sys.excepthook = except_hook
  5301. # Terminate on timeout
  5302. if timeout is not None:
  5303. QtCore.QTimer.singleShot(timeout, report_quit)
  5304. #### Block ####
  5305. loop.exec_()
  5306. # Restore exception management
  5307. sys.excepthook = oeh
  5308. if ex:
  5309. self.raiseTclError(str(ex[0]))
  5310. if status['timed_out']:
  5311. raise Exception('Timed out!')
  5312. def make_docs():
  5313. output = ''
  5314. import collections
  5315. od = collections.OrderedDict(sorted(commands.items()))
  5316. for cmd_, val in od.items():
  5317. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  5318. t = val['help']
  5319. usage_i = t.find('>')
  5320. if usage_i < 0:
  5321. expl = t
  5322. output += expl + '\n\n'
  5323. continue
  5324. expl = t[:usage_i - 1]
  5325. output += expl + '\n\n'
  5326. end_usage_i = t[usage_i:].find('\n')
  5327. if end_usage_i < 0:
  5328. end_usage_i = len(t[usage_i:])
  5329. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  5330. else:
  5331. extras = t[usage_i+end_usage_i+1:]
  5332. parts = [s.strip() for s in extras.split('\n')]
  5333. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  5334. for p in parts:
  5335. output += ' ' + p + '\n\n'
  5336. return output
  5337. '''
  5338. Howto implement TCL shell commands:
  5339. All parameters passed to command should be possible to set as None and test it afterwards.
  5340. This is because we need to see error caused in tcl,
  5341. if None value as default parameter is not allowed TCL will return empty error.
  5342. Use:
  5343. def mycommand(name=None,...):
  5344. Test it like this:
  5345. if name is None:
  5346. self.raise_tcl_error('Argument name is missing.')
  5347. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  5348. otherwise we will miss it and processing will silently continue.
  5349. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  5350. which is catched in exec_command and displayed in TCL shell console with red background.
  5351. Error in console is displayed with TCL trace.
  5352. This behavior works only within main thread,
  5353. errors with promissed tasks can be catched and detected only with log.
  5354. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for TCL shell.
  5355. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  5356. '''
  5357. commands = {
  5358. 'help': {
  5359. 'fcn': shelp,
  5360. 'help': "Shows list of commands."
  5361. },
  5362. }
  5363. # Import/overwrite tcl commands as objects of TclCommand descendants
  5364. # This modifies the variable 'commands'.
  5365. tclCommands.register_all_commands(self, commands)
  5366. # Add commands to the tcl interpreter
  5367. for cmd in commands:
  5368. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  5369. # Make the tcl puts function return instead of print to stdout
  5370. self.tcl.eval('''
  5371. rename puts original_puts
  5372. proc puts {args} {
  5373. if {[llength $args] == 1} {
  5374. return "[lindex $args 0]"
  5375. } else {
  5376. eval original_puts $args
  5377. }
  5378. }
  5379. ''')
  5380. def setup_recent_items(self):
  5381. # TODO: Move this to constructor
  5382. icons = {
  5383. "gerber": "share/flatcam_icon16.png",
  5384. "excellon": "share/drill16.png",
  5385. "cncjob": "share/cnc16.png",
  5386. "project": "share/project16.png",
  5387. "svg": "share/geometry16.png",
  5388. "dxf": "share/dxf16.png",
  5389. "image": "share/image16.png"
  5390. }
  5391. openers = {
  5392. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  5393. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  5394. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  5395. 'project': self.open_project,
  5396. 'svg': self.import_svg,
  5397. 'dxf': self.import_dxf,
  5398. 'image': self.import_image
  5399. }
  5400. # Open file
  5401. try:
  5402. f = open(self.data_path + '/recent.json')
  5403. except IOError:
  5404. App.log.error("Failed to load recent item list.")
  5405. self.inform.emit("[ERROR_NOTCL] Failed to load recent item list.")
  5406. return
  5407. try:
  5408. self.recent = json.load(f)
  5409. except json.scanner.JSONDecodeError:
  5410. App.log.error("Failed to parse recent item list.")
  5411. self.inform.emit("[ERROR_NOTCL] Failed to parse recent item list.")
  5412. f.close()
  5413. return
  5414. f.close()
  5415. # Closure needed to create callbacks in a loop.
  5416. # Otherwise late binding occurs.
  5417. def make_callback(func, fname):
  5418. def opener():
  5419. func(fname)
  5420. return opener
  5421. def reset_recent():
  5422. # Reset menu
  5423. self.ui.recent.clear()
  5424. self.recent = []
  5425. try:
  5426. f = open(self.data_path + '/recent.json', 'w')
  5427. except IOError:
  5428. App.log.error("Failed to open recent items file for writing.")
  5429. return
  5430. json.dump(self.recent, f)
  5431. # Reset menu
  5432. self.ui.recent.clear()
  5433. # Create menu items
  5434. for recent in self.recent:
  5435. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  5436. try:
  5437. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  5438. # Attach callback
  5439. o = make_callback(openers[recent["kind"]], recent['filename'])
  5440. action.triggered.connect(o)
  5441. self.ui.recent.addAction(action)
  5442. except KeyError:
  5443. App.log.error("Unsupported file type: %s" % recent["kind"])
  5444. # Last action in Recent Files menu is one that Clear the content
  5445. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), "Clear Recent files", self)
  5446. clear_action.triggered.connect(reset_recent)
  5447. self.ui.recent.addSeparator()
  5448. self.ui.recent.addAction(clear_action)
  5449. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  5450. # self.ui.menufilerecent.set_submenu(recent_menu)
  5451. # recent_menu.show_all()
  5452. # self.ui.recent.show()
  5453. self.log.debug("Recent items list has been populated.")
  5454. def setup_component_editor(self):
  5455. # label = QtWidgets.QLabel("Choose an item from Project")
  5456. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  5457. sel_title = QtWidgets.QTextEdit(
  5458. '<b>Shortcut Key List</b>')
  5459. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  5460. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  5461. # font = self.sel_title.font()
  5462. # font.setPointSize(12)
  5463. # self.sel_title.setFont(font)
  5464. selected_text = '''
  5465. <p><span style="font-size:14px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  5466. <p><span style="font-size:10px"><strong>Details</strong>:<br />
  5467. The normal flow when working in FlatCAM is the following:</span></p>
  5468. <ol>
  5469. <li><span style="font-size:10px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM using either the menu&#39;s, toolbars, key shortcuts or even dragging and dropping the files on the GUI.<br />
  5470. <br />
  5471. You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  5472. &nbsp;</li>
  5473. <li><span style="font-size:10px">Once an object is available in the Project Tab, by selecting it and then focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  5474. <br />
  5475. If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong> is in focus, again the object properties will be displayed into the Selected Tab. Alternatively, double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate it even if it was out of focus.<br />
  5476. <br />
  5477. You can change the parameters in this screen and the flow direction is like this:<br />
  5478. <br />
  5479. <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  5480. </ol>
  5481. <p><span style="font-size:10px">A list of key shortcuts is available through an menu entry in <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut: <strng>F3</strong>.</span></p>
  5482. '''
  5483. sel_title.setText(selected_text)
  5484. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  5485. self.ui.selected_scroll_area.setWidget(sel_title)
  5486. # tool_title = QtWidgets.QTextEdit(
  5487. # '<b>Shortcut Key List</b>')
  5488. # tool_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  5489. # tool_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  5490. # # font = self.sel_title.font()
  5491. # # font.setPointSize(12)
  5492. # # self.sel_title.setFont(font)
  5493. #
  5494. # tool_text = '''
  5495. # <p><span style="font-size:14px"><strong>Tool Tab - Choose an Item in Tools Menu</strong></span></p>
  5496. #
  5497. # <p><span style="font-size:10px"><strong>Details</strong>:<br />
  5498. # Some of the functionality of FlatCAM have been implemented as tools (a sort of plugins). </span></p>
  5499. #
  5500. # <p><span style="font-size:10px">Most of the tools are accessible through&nbsp;the Tools menu or by using the associated shortcut keys.<br />
  5501. # Each such a tool, if it needs an object to be used as a source it will provide the way to select this object(s) through a series of comboboxes. The result of using a tool is either a Geometry, an information that can be used in the app or it can be a file that can be saved.</span></p>
  5502. #
  5503. # <ol>
  5504. # </ol>
  5505. #
  5506. # <p><span style="font-size:10px">A list of key shortcuts is available through an menu entry in <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut: &#39;`&#39; (key left to 1).</span></p>
  5507. #
  5508. # '''
  5509. #
  5510. # tool_title.setText(tool_text)
  5511. # tool_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  5512. #
  5513. # self.ui.tool_scroll_area.setWidget(tool_title)
  5514. def setup_obj_classes(self):
  5515. """
  5516. Sets up application specifics on the FlatCAMObj class.
  5517. :return: None
  5518. """
  5519. FlatCAMObj.app = self
  5520. ObjectCollection.app = self
  5521. FCProcess.app = self
  5522. FCProcessContainer.app = self
  5523. def version_check(self):
  5524. """
  5525. Checks for the latest version of the program. Alerts the
  5526. user if theirs is outdated. This method is meant to be run
  5527. in a separate thread.
  5528. :return: None
  5529. """
  5530. self.log.debug("version_check()")
  5531. if self.general_defaults_form.general_gui_group.send_stats_cb.get_value() is True:
  5532. full_url = App.version_url + \
  5533. "?s=" + str(self.defaults['global_serial']) + \
  5534. "&v=" + str(self.version) + \
  5535. "&os=" + str(self.os) + \
  5536. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  5537. else:
  5538. # no_stats dict; just so it won't break things on website
  5539. no_ststs_dict = {}
  5540. no_ststs_dict["global_ststs"] = {}
  5541. full_url = App.version_url + \
  5542. "?s=" + str(self.defaults['global_serial']) + \
  5543. "&v=" + str(self.version) + \
  5544. "&os=" + str(self.os) + \
  5545. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  5546. App.log.debug("Checking for updates @ %s" % full_url)
  5547. ### Get the data
  5548. try:
  5549. f = urllib.request.urlopen(full_url)
  5550. except:
  5551. # App.log.warning("Failed checking for latest version. Could not connect.")
  5552. self.log.warning("Failed checking for latest version. Could not connect.")
  5553. self.inform.emit("[WARNING_NOTCL] Failed checking for latest version. Could not connect.")
  5554. return
  5555. try:
  5556. data = json.load(f)
  5557. except Exception as e:
  5558. App.log.error("Could not parse information about latest version.")
  5559. self.inform.emit("[ERROR_NOTCL] Could not parse information about latest version.")
  5560. App.log.debug("json.load(): %s" % str(e))
  5561. f.close()
  5562. return
  5563. f.close()
  5564. ### Latest version?
  5565. if self.version >= data["version"]:
  5566. App.log.debug("FlatCAM is up to date!")
  5567. self.inform.emit("[success] FlatCAM is up to date!")
  5568. return
  5569. App.log.debug("Newer version available.")
  5570. self.message.emit(
  5571. "Newer Version Available",
  5572. str("There is a newer version of FlatCAM " +
  5573. "available for download:<br><br>" +
  5574. "<B>" + data["name"] + "</b><br>" +
  5575. data["message"].replace("\n", "<br>")),
  5576. "info"
  5577. )
  5578. def on_zoom_fit(self, event):
  5579. """
  5580. Callback for zoom-out request. This can be either from the corresponding
  5581. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  5582. with axes limits from the geometry bounds of all objects.
  5583. :param event: Ignored.
  5584. :return: None
  5585. """
  5586. self.plotcanvas.fit_view()
  5587. def disable_all_plots(self):
  5588. self.report_usage("disable_all_plots()")
  5589. self.disable_plots(self.collection.get_list())
  5590. self.inform.emit("[success]All plots disabled.")
  5591. def disable_other_plots(self):
  5592. self.report_usage("disable_other_plots()")
  5593. self.disable_plots(self.collection.get_non_selected())
  5594. self.inform.emit("[success]All non selected plots disabled.")
  5595. def enable_all_plots(self):
  5596. self.report_usage("enable_all_plots()")
  5597. self.enable_plots(self.collection.get_list())
  5598. self.inform.emit("[success]All plots enabled.")
  5599. # TODO: FIX THIS
  5600. '''
  5601. By default this is not threaded
  5602. If threaded the app give warnings like this:
  5603. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  5604. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  5605. '''
  5606. def enable_plots(self, objects, threaded=False):
  5607. if threaded is True:
  5608. def worker_task(app_obj):
  5609. percentage = 0.1
  5610. try:
  5611. delta = 0.9 / len(objects)
  5612. except ZeroDivisionError:
  5613. self.progress.emit(0)
  5614. return
  5615. for obj in objects:
  5616. obj.options['plot'] = True
  5617. percentage += delta
  5618. self.progress.emit(int(percentage*100))
  5619. self.progress.emit(0)
  5620. self.plots_updated.emit()
  5621. self.collection.update_view()
  5622. # Send to worker
  5623. # self.worker.add_task(worker_task, [self])
  5624. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  5625. else:
  5626. for obj in objects:
  5627. obj.options['plot'] = True
  5628. self.progress.emit(0)
  5629. self.plots_updated.emit()
  5630. self.collection.update_view()
  5631. # TODO: FIX THIS
  5632. '''
  5633. By default this is not threaded
  5634. If threaded the app give warnings like this:
  5635. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  5636. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  5637. '''
  5638. def disable_plots(self, objects, threaded=False):
  5639. # TODO: This method is very similar to replot_all. Try to merge.
  5640. """
  5641. Disables plots
  5642. :param objects: list
  5643. Objects to be disabled
  5644. :return:
  5645. """
  5646. if threaded is True:
  5647. self.progress.emit(10)
  5648. def worker_task(app_obj):
  5649. percentage = 0.1
  5650. try:
  5651. delta = 0.9 / len(objects)
  5652. except ZeroDivisionError:
  5653. self.progress.emit(0)
  5654. return
  5655. for obj in objects:
  5656. obj.options['plot'] = False
  5657. percentage += delta
  5658. self.progress.emit(int(percentage*100))
  5659. self.progress.emit(0)
  5660. self.plots_updated.emit()
  5661. self.collection.update_view()
  5662. # Send to worker
  5663. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  5664. else:
  5665. for obj in objects:
  5666. obj.options['plot'] = False
  5667. self.plots_updated.emit()
  5668. self.collection.update_view()
  5669. def clear_plots(self):
  5670. objects = self.collection.get_list()
  5671. for obj in objects:
  5672. obj.clear(obj == objects[-1])
  5673. # Clear pool to free memory
  5674. self.clear_pool()
  5675. def generate_cnc_job(self, objects):
  5676. self.report_usage("generate_cnc_job()")
  5677. # for obj in objects:
  5678. # obj.generatecncjob()
  5679. for obj in objects:
  5680. obj.on_generatecnc_button_click()
  5681. def save_project(self, filename):
  5682. """
  5683. Saves the current project to the specified file.
  5684. :param filename: Name of the file in which to save.
  5685. :type filename: str
  5686. :return: None
  5687. """
  5688. self.log.debug("save_project()")
  5689. with self.proc_container.new("Saving FlatCAM Project") as proc:
  5690. ## Capture the latest changes
  5691. # Current object
  5692. try:
  5693. self.collection.get_active().read_form()
  5694. except:
  5695. self.log.debug("[WARNING] There was no active object")
  5696. pass
  5697. # Project options
  5698. self.options_read_form()
  5699. # Serialize the whole project
  5700. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  5701. "options": self.options,
  5702. "version": self.version}
  5703. if self.defaults["global_save_compressed"] is True:
  5704. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  5705. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  5706. # # Write
  5707. f.write(g)
  5708. self.inform.emit("[success] Project saved to: %s" % filename)
  5709. else:
  5710. # Open file
  5711. try:
  5712. f = open(filename, 'w')
  5713. except IOError:
  5714. App.log.error("[ERROR] Failed to open file for saving: %s", filename)
  5715. return
  5716. # Write
  5717. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  5718. f.close()
  5719. # verification of the saved project
  5720. # Open and parse
  5721. try:
  5722. saved_f = open(filename, 'r')
  5723. except IOError:
  5724. self.inform.emit("[ERROR_NOTCL] Failed to verify project file: %s. Retry to save it." % filename)
  5725. return
  5726. try:
  5727. saved_d = json.load(saved_f, object_hook=dict2obj)
  5728. except:
  5729. self.inform.emit(
  5730. "[ERROR_NOTCL] Failed to parse saved project file: %s. Retry to save it." % filename)
  5731. f.close()
  5732. return
  5733. saved_f.close()
  5734. if 'version' in saved_d:
  5735. self.inform.emit("[success] Project saved to: %s" % filename)
  5736. else:
  5737. self.inform.emit("[ERROR_NOTCL] Failed to save project file: %s. Retry to save it." % filename)
  5738. def on_options_app2project(self):
  5739. """
  5740. Callback for Options->Transfer Options->App=>Project. Copies options
  5741. from application defaults to project defaults.
  5742. :return: None
  5743. """
  5744. self.report_usage("on_options_app2project")
  5745. self.defaults_read_form()
  5746. self.options.update(self.defaults)
  5747. self.options_write_form()
  5748. def on_options_project2app(self):
  5749. """
  5750. Callback for Options->Transfer Options->Project=>App. Copies options
  5751. from project defaults to application defaults.
  5752. :return: None
  5753. """
  5754. self.report_usage("on_options_project2app")
  5755. self.options_read_form()
  5756. self.defaults.update(self.options)
  5757. self.defaults_write_form()
  5758. def on_options_project2object(self):
  5759. """
  5760. Callback for Options->Transfer Options->Project=>Object. Copies options
  5761. from project defaults to the currently selected object.
  5762. :return: None
  5763. """
  5764. self.report_usage("on_options_project2object")
  5765. self.options_read_form()
  5766. obj = self.collection.get_active()
  5767. if obj is None:
  5768. self.inform.emit("WARNING: No object selected.")
  5769. return
  5770. for option in self.options:
  5771. if option.find(obj.kind + "_") == 0:
  5772. oname = option[len(obj.kind) + 1:]
  5773. obj.options[oname] = self.options[option]
  5774. obj.to_form() # Update UI
  5775. def on_options_object2project(self):
  5776. """
  5777. Callback for Options->Transfer Options->Object=>Project. Copies options
  5778. from the currently selected object to project defaults.
  5779. :return: None
  5780. """
  5781. self.report_usage("on_options_object2project")
  5782. obj = self.collection.get_active()
  5783. if obj is None:
  5784. self.inform.emit("WARNING: No object selected.")
  5785. return
  5786. obj.read_form()
  5787. for option in obj.options:
  5788. if option in ['name']: # TODO: Handle this better...
  5789. continue
  5790. self.options[obj.kind + "_" + option] = obj.options[option]
  5791. self.options_write_form()
  5792. def on_options_object2app(self):
  5793. """
  5794. Callback for Options->Transfer Options->Object=>App. Copies options
  5795. from the currently selected object to application defaults.
  5796. :return: None
  5797. """
  5798. self.report_usage("on_options_object2app")
  5799. obj = self.collection.get_active()
  5800. if obj is None:
  5801. self.inform.emit("WARNING: No object selected.")
  5802. return
  5803. obj.read_form()
  5804. for option in obj.options:
  5805. if option in ['name']: # TODO: Handle this better...
  5806. continue
  5807. self.defaults[obj.kind + "_" + option] = obj.options[option]
  5808. self.defaults_write_form()
  5809. def on_options_app2object(self):
  5810. """
  5811. Callback for Options->Transfer Options->App=>Object. Copies options
  5812. from application defaults to the currently selected object.
  5813. :return: None
  5814. """
  5815. self.report_usage("on_options_app2object")
  5816. self.defaults_read_form()
  5817. obj = self.collection.get_active()
  5818. if obj is None:
  5819. self.inform.emit("WARNING: No object selected.")
  5820. return
  5821. for option in self.defaults:
  5822. if option.find(obj.kind + "_") == 0:
  5823. oname = option[len(obj.kind) + 1:]
  5824. obj.options[oname] = self.defaults[option]
  5825. obj.to_form() # Update UI
  5826. # end of file