FlatCAMApp.py 514 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429
  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 urllib.request
  9. import urllib.parse
  10. import urllib.error
  11. import getopt
  12. import random
  13. import simplejson as json
  14. import lzma
  15. import threading
  16. import shutil
  17. from stat import S_IREAD, S_IRGRP, S_IROTH
  18. import subprocess
  19. import ctypes
  20. import tkinter as tk
  21. from PyQt5 import QtPrintSupport
  22. from contextlib import contextmanager
  23. import gc
  24. from xml.dom.minidom import parseString as parse_xml_string
  25. from multiprocessing.connection import Listener, Client
  26. from multiprocessing import Pool
  27. import socket
  28. from array import array
  29. # #######################################
  30. # # Imports part of FlatCAM ##
  31. # #######################################
  32. from ObjectCollection import *
  33. from FlatCAMObj import *
  34. from flatcamGUI.PlotCanvas import *
  35. from flatcamGUI.PlotCanvasLegacy import *
  36. from flatcamGUI.FlatCAMGUI import *
  37. from FlatCAMCommon import LoudDict
  38. from FlatCAMPostProc import load_postprocessors
  39. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  40. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  41. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  42. from FlatCAMProcess import *
  43. from FlatCAMWorkerStack import WorkerStack
  44. from flatcamGUI.VisPyVisuals import Color
  45. from vispy.gloo.util import _screenshot
  46. from vispy.io import write_png
  47. from flatcamTools import *
  48. import tclCommands
  49. import gettext
  50. import FlatCAMTranslation as fcTranslate
  51. import builtins
  52. if sys.platform == 'win32':
  53. import winreg
  54. fcTranslate.apply_language('strings')
  55. if '_' not in builtins.__dict__:
  56. _ = gettext.gettext
  57. # ########################################
  58. # # App ###
  59. # ########################################
  60. class App(QtCore.QObject):
  61. """
  62. The main application class. The constructor starts the GUI.
  63. """
  64. # Get Cmd Line Options
  65. cmd_line_shellfile = ''
  66. cmd_line_shellvar = ''
  67. cmd_line_headless = None
  68. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  69. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  70. "FlatCam.py --headless=1"
  71. try:
  72. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  73. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  74. "shellvar=",
  75. "headless=",
  76. "multiprocessing-fork="])
  77. except getopt.GetoptError:
  78. print(cmd_line_help)
  79. sys.exit(2)
  80. for opt, arg in cmd_line_options:
  81. if opt == '-h':
  82. print(cmd_line_help)
  83. sys.exit()
  84. elif opt == '--shellfile':
  85. cmd_line_shellfile = arg
  86. elif opt == '--shellvar':
  87. cmd_line_shellvar = arg
  88. elif opt == '--headless':
  89. try:
  90. cmd_line_headless = eval(arg)
  91. except NameError:
  92. pass
  93. # ## Logging ###
  94. log = logging.getLogger('base')
  95. log.setLevel(logging.DEBUG)
  96. # log.setLevel(logging.WARNING)
  97. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  98. handler = logging.StreamHandler()
  99. handler.setFormatter(formatter)
  100. log.addHandler(handler)
  101. # ##########################################################################
  102. # ################## Version and VERSION DATE ##############################
  103. # ##########################################################################
  104. version = 8.97
  105. version_date = "2019/09/20"
  106. beta = True
  107. # current date now
  108. date = str(datetime.today()).rpartition('.')[0]
  109. date = ''.join(c for c in date if c not in ':-')
  110. date = date.replace(' ', '_')
  111. # URL for update checks and statistics
  112. version_url = "http://flatcam.org/version"
  113. # App URL
  114. app_url = "http://flatcam.org"
  115. # Manual URL
  116. manual_url = "http://flatcam.org/manual/index.html"
  117. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  118. gerber_spec_url ="https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  119. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  120. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  121. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  122. # this variable will hold the project status
  123. # if True it will mean that the project was modified and not saved
  124. should_we_save = False
  125. # flag is True if saving action has been triggered
  126. save_in_progress = False
  127. # ###########################################################################
  128. # ############################# Signals ################################
  129. # ###########################################################################
  130. # Inform the user
  131. # Handled by:
  132. # * App.info() --> Print on the status bar
  133. inform = QtCore.pyqtSignal(str)
  134. app_quit = QtCore.pyqtSignal()
  135. # General purpose background task
  136. worker_task = QtCore.pyqtSignal(dict)
  137. # File opened
  138. # Handled by:
  139. # * register_folder()
  140. # * register_recent()
  141. # Note: Setting the parameters to unicode does not seem
  142. # to have an effect. Then are received as Qstring
  143. # anyway.
  144. # File type and filename
  145. file_opened = QtCore.pyqtSignal(str, str)
  146. # File type and filename
  147. file_saved = QtCore.pyqtSignal(str, str)
  148. # Percentage of progress
  149. progress = QtCore.pyqtSignal(int)
  150. plots_updated = QtCore.pyqtSignal()
  151. # Emitted by new_object() and passes the new object as argument, plot flag.
  152. # on_object_created() adds the object to the collection, plots on appropriate flag
  153. # and emits new_object_available.
  154. object_created = QtCore.pyqtSignal(object, bool, bool)
  155. # Emitted when a object has been changed (like scaled, mirrored)
  156. object_changed = QtCore.pyqtSignal(object)
  157. # Emitted after object has been plotted.
  158. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  159. object_plotted = QtCore.pyqtSignal(object)
  160. # Emitted when a new object has been added or deleted from/to the collection
  161. object_status_changed = QtCore.pyqtSignal(object, str)
  162. message = QtCore.pyqtSignal(str, str, str)
  163. # Emmited when shell command is finished(one command only)
  164. shell_command_finished = QtCore.pyqtSignal(object)
  165. # Emitted when multiprocess pool has been recreated
  166. pool_recreated = QtCore.pyqtSignal(object)
  167. # Emitted when an unhandled exception happens
  168. # in the worker task.
  169. thread_exception = QtCore.pyqtSignal(object)
  170. # used to signal that there are arguments for the app
  171. args_at_startup = QtCore.pyqtSignal(list)
  172. # a reusable signal to replot a list of objects
  173. # should be disconnected after use so it can be reused
  174. replot_signal = pyqtSignal(list)
  175. def __init__(self, user_defaults=True, post_gui=None):
  176. """
  177. Starts the application.
  178. :return: app
  179. :rtype: App
  180. """
  181. App.log.info("FlatCAM Starting...")
  182. self.main_thread = QtWidgets.QApplication.instance().thread()
  183. # ############################################################################
  184. # # ################# OS-specific ############################################
  185. # ############################################################################
  186. portable = False
  187. # Folder for user settings.
  188. if sys.platform == 'win32':
  189. # #########################################################################
  190. # Setup the listening thread for another instance launching with args #####
  191. # #########################################################################
  192. # make sure the thread is stored by using a self. otherwise it's garbage collected
  193. self.th = QtCore.QThread()
  194. self.th.start(priority=QtCore.QThread.LowestPriority)
  195. self.new_launch = ArgsThread()
  196. self.new_launch.open_signal[list].connect(self.on_startup_args)
  197. self.new_launch.moveToThread(self.th)
  198. self.new_launch.start.emit()
  199. from win32com.shell import shell, shellcon
  200. if platform.architecture()[0] == '32bit':
  201. App.log.debug("Win32!")
  202. else:
  203. App.log.debug("Win64!")
  204. # #########################################################################
  205. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY ###############
  206. # #########################################################################
  207. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  208. try:
  209. with open(config_file, 'r'):
  210. pass
  211. except FileNotFoundError:
  212. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  213. try:
  214. with open(config_file, 'r') as f:
  215. try:
  216. for line in f:
  217. param = str(line).replace('\n', '').rpartition('=')
  218. if param[0] == 'portable':
  219. try:
  220. portable = eval(param[2])
  221. except NameError:
  222. portable = False
  223. if param[0] == 'headless':
  224. if param[2].lower() == 'true':
  225. self.cmd_line_headless = 1
  226. else:
  227. self.cmd_line_headless = None
  228. except Exception as e:
  229. log.debug('App.__init__() -->%s' % str(e))
  230. return
  231. except FileNotFoundError as e:
  232. log.debug(str(e))
  233. pass
  234. if portable is False:
  235. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  236. else:
  237. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  238. self.os = 'windows'
  239. else: # Linux/Unix/MacOS
  240. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  241. self.os = 'unix'
  242. # ##########################################################################
  243. # ################## Setup folders and files ###############################
  244. # ##########################################################################
  245. if not os.path.exists(self.data_path):
  246. os.makedirs(self.data_path)
  247. App.log.debug('Created data folder: ' + self.data_path)
  248. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  249. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  250. self.postprocessorpaths = os.path.join(self.data_path, 'postprocessors')
  251. if not os.path.exists(self.postprocessorpaths):
  252. os.makedirs(self.postprocessorpaths)
  253. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  254. # create current_defaults.FlatConfig file if there is none
  255. try:
  256. f = open(self.data_path + '/current_defaults.FlatConfig')
  257. f.close()
  258. except IOError:
  259. App.log.debug('Creating empty current_defaults.FlatConfig')
  260. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  261. json.dump({}, f)
  262. f.close()
  263. # create factory_defaults.FlatConfig file if there is none
  264. try:
  265. f = open(self.data_path + '/factory_defaults.FlatConfig')
  266. f.close()
  267. except IOError:
  268. App.log.debug('Creating empty factory_defaults.FlatConfig')
  269. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  270. json.dump({}, f)
  271. f.close()
  272. # create a recent files json file if there is none
  273. try:
  274. f = open(self.data_path + '/recent.json')
  275. f.close()
  276. except IOError:
  277. App.log.debug('Creating empty recent.json')
  278. f = open(self.data_path + '/recent.json', 'w')
  279. json.dump([], f)
  280. f.close()
  281. # create a recent projects json file if there is none
  282. try:
  283. fp = open(self.data_path + '/recent_projects.json')
  284. fp.close()
  285. except IOError:
  286. App.log.debug('Creating empty recent_projects.json')
  287. fp = open(self.data_path + '/recent_projects.json', 'w')
  288. json.dump([], fp)
  289. fp.close()
  290. # Application directory. CHDIR to it. Otherwise, trying to load
  291. # GUI icons will fail as their path is relative.
  292. # This will fail under cx_freeze ...
  293. self.app_home = os.path.dirname(os.path.realpath(__file__))
  294. App.log.debug("Application path is " + self.app_home)
  295. App.log.debug("Started in " + os.getcwd())
  296. # cx_freeze workaround
  297. if os.path.isfile(self.app_home):
  298. self.app_home = os.path.dirname(self.app_home)
  299. os.chdir(self.app_home)
  300. # #############################################################################
  301. # ##################### CREATE MULTIPROCESSING POOL ###########################
  302. # #############################################################################
  303. self.pool = Pool()
  304. # ##########################################################################
  305. # ################## Setting the Splash Screen #############################
  306. # ##########################################################################
  307. settings = QSettings("Open Source", "FlatCAM")
  308. if settings.contains("splash_screen"):
  309. show_splash = settings.value("splash_screen")
  310. else:
  311. settings.setValue('splash_screen', 1)
  312. # This will write the setting to the platform specific storage.
  313. del settings
  314. show_splash = 1
  315. if show_splash and self.cmd_line_headless != 1:
  316. splash_pix = QtGui.QPixmap('share/splash.png')
  317. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  318. # self.splash.setMask(splash_pix.mask())
  319. # move splashscreen to the current monitor
  320. desktop = QtWidgets.QApplication.desktop()
  321. screen = desktop.screenNumber(QtGui.QCursor.pos())
  322. current_screen_center = desktop.availableGeometry(screen).center()
  323. self.splash.move(current_screen_center - self.splash.rect().center())
  324. self.splash.show()
  325. self.splash.showMessage(_("FlatCAM is initializing ..."),
  326. alignment=Qt.AlignBottom | Qt.AlignLeft,
  327. color=QtGui.QColor("gray"))
  328. else:
  329. show_splash = 0
  330. # #############################################################################
  331. # ##################### Initialize GUI ########################################
  332. # #############################################################################
  333. # FlatCAM colors used in plotting
  334. self.FC_light_green = '#BBF268BF'
  335. self.FC_dark_green = '#006E20BF'
  336. self.FC_light_blue = '#a5a5ffbf'
  337. self.FC_dark_blue = '#0000ffbf'
  338. QtCore.QObject.__init__(self)
  339. self.ui = FlatCAMGUI(self.version, self.beta, self)
  340. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  341. self.ui.final_save.connect(self.final_save)
  342. # #############################################################################
  343. # ############################## Data #########################################
  344. # #############################################################################
  345. self.recent = []
  346. self.recent_projects = []
  347. self.clipboard = QtWidgets.QApplication.clipboard()
  348. self.project_filename = None
  349. self.toggle_units_ignore = False
  350. # self.defaults_form = PreferencesUI()
  351. # when adding entries here read the comments in the method found bellow named:
  352. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  353. self.defaults_form_fields = {
  354. # General App
  355. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  356. "global_graphic_engine": self.ui.general_defaults_form.general_app_group.ge_radio,
  357. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  358. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  359. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  360. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  361. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  362. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  363. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  364. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  365. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  366. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  367. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_combo,
  368. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  369. # General GUI Preferences
  370. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  371. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  372. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  373. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  374. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  375. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  376. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  377. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  378. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  379. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  380. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  381. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  382. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  383. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  384. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  385. "global_activity_icon": self.ui.general_defaults_form.general_gui_group.activity_combo,
  386. # General GUI Settings
  387. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  388. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  389. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  390. "global_systray_icon": self.ui.general_defaults_form.general_gui_set_group.systray_cb,
  391. "global_shell_at_startup": self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb,
  392. "global_project_at_startup": self.ui.general_defaults_form.general_gui_set_group.project_startup_cb,
  393. "global_project_autohide": self.ui.general_defaults_form.general_gui_set_group.project_autohide_cb,
  394. "global_toggle_tooltips": self.ui.general_defaults_form.general_gui_set_group.toggle_tooltips_cb,
  395. "global_delete_confirmation": self.ui.general_defaults_form.general_gui_set_group.delete_conf_cb,
  396. # Gerber General
  397. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  398. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  399. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  400. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  401. # Gerber Options
  402. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  403. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  404. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  405. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  406. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  407. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  408. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  409. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  410. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  411. # Gerber Advanced Options
  412. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  413. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  414. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  415. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  416. "gerber_buffering": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffering_radio,
  417. "gerber_simplification": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplify_cb,
  418. "gerber_simp_tolerance": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplification_tol_spinner,
  419. # Gerber Export
  420. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  421. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  422. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  423. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  424. # Gerber Editor
  425. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  426. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  427. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  428. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  429. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  430. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  431. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  432. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  433. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  434. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  435. "gerber_editor_circ_angle":
  436. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  437. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  438. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  439. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  440. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  441. # Excellon General
  442. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  443. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  444. "excellon_format_upper_in":
  445. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  446. "excellon_format_lower_in":
  447. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  448. "excellon_format_upper_mm":
  449. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  450. "excellon_format_lower_mm":
  451. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  452. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  453. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  454. "excellon_update": self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb,
  455. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  456. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  457. # Excellon Options
  458. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  459. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  460. "excellon_endz": self.ui.excellon_defaults_form.excellon_opt_group.eendz_entry,
  461. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  462. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  463. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  464. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  465. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  466. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  467. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  468. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  469. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  470. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  471. # Excellon Advanced Options
  472. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  473. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  474. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  475. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  476. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  477. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  478. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_adv_opt_group.spindledir_radio,
  479. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  480. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  481. # Excellon Export
  482. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  483. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  484. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  485. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  486. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  487. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  488. # Excellon Editor
  489. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  490. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  491. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  492. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  493. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  494. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  495. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  496. "excellon_editor_circ_angle":
  497. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  498. # Excellon Slots
  499. "excellon_editor_slot_direction":
  500. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  501. "excellon_editor_slot_angle":
  502. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  503. "excellon_editor_slot_length":
  504. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  505. # Excellon Slots
  506. "excellon_editor_slot_array_size":
  507. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  508. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  509. "excellon_editor_slot_lin_pitch":
  510. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  511. "excellon_editor_slot_lin_angle":
  512. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  513. "excellon_editor_slot_circ_dir":
  514. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  515. "excellon_editor_slot_circ_angle":
  516. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  517. # Geometry General
  518. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  519. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  520. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  521. # Geometry Options
  522. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  523. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  524. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  525. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  526. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  527. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  528. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  529. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  530. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  531. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  532. "geometry_endz": self.ui.geometry_defaults_form.geometry_opt_group.gendz_entry,
  533. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  534. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  535. # Geometry Advanced Options
  536. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  537. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  538. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  539. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  540. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  541. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  542. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_adv_opt_group.spindledir_radio,
  543. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  544. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  545. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  546. # Geometry Editor
  547. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  548. # CNCJob General
  549. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  550. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  551. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  552. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  553. "cncjob_coords_type": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_type_radio,
  554. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  555. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  556. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  557. # CNC Job Options
  558. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  559. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  560. # CNC Job Advanced Options
  561. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  562. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  563. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontsize_sp,
  564. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry,
  565. # NCC Tool
  566. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  567. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  568. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  569. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  570. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  571. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  572. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  573. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  574. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  575. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  576. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.reference_radio,
  577. "tools_ncc_plotting": self.ui.tools_defaults_form.tools_ncc_group.ncc_plotting_radio,
  578. "tools_nccmilling_type": self.ui.tools_defaults_form.tools_ncc_group.milling_type_radio,
  579. "tools_ncctool_type": self.ui.tools_defaults_form.tools_ncc_group.tool_type_radio,
  580. "tools_ncccutz": self.ui.tools_defaults_form.tools_ncc_group.cutz_entry,
  581. "tools_ncctipdia": self.ui.tools_defaults_form.tools_ncc_group.tipdia_entry,
  582. "tools_ncctipangle": self.ui.tools_defaults_form.tools_ncc_group.tipangle_entry,
  583. # CutOut Tool
  584. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  585. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  586. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  587. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  588. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  589. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  590. # Paint Area Tool
  591. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  592. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  593. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  594. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  595. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  596. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  597. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  598. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  599. "tools_paint_plotting": self.ui.tools_defaults_form.tools_paint_group.paint_plotting_radio,
  600. # 2-sided Tool
  601. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  602. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  603. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  604. # Film Tool
  605. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  606. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  607. "tools_film_scale": self.ui.tools_defaults_form.tools_film_group.film_scale_entry,
  608. "tools_film_color": self.ui.tools_defaults_form.tools_film_group.film_color_entry,
  609. # Panelize Tool
  610. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  611. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  612. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  613. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  614. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  615. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  616. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  617. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  618. # Calculators Tool
  619. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  620. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  621. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  622. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  623. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  624. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  625. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  626. # Transformations Tool
  627. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  628. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  629. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  630. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  631. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  632. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  633. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  634. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  635. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  636. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  637. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  638. # SolderPaste Dispensing Tool
  639. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  640. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  641. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  642. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  643. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  644. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  645. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  646. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  647. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  648. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  649. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  650. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  651. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  652. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  653. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  654. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  655. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb,
  656. # Utilities
  657. # File associations
  658. "fa_excellon": self.ui.util_defaults_form.fa_excellon_group.exc_list_text,
  659. "fa_gcode": self.ui.util_defaults_form.fa_gcode_group.gco_list_text,
  660. # "fa_geometry": self.ui.util_defaults_form.fa_geometry_group.close_paths_cb,
  661. "fa_gerber": self.ui.util_defaults_form.fa_gerber_group.grb_list_text,
  662. "util_autocomplete_keywords": self.ui.util_defaults_form.kw_group.kw_list_text,
  663. }
  664. # ############################
  665. # ### LOAD POSTPROCESSORS ####
  666. # ############################
  667. self.postprocessors = load_postprocessors(self)
  668. for name in list(self.postprocessors.keys()):
  669. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  670. if name.partition('_')[0] == 'Paste':
  671. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  672. continue
  673. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  674. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  675. if name == 'hpgl':
  676. continue
  677. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  678. # ############################
  679. # ### LOAD LANGUAGES ####
  680. # ############################
  681. self.languages = fcTranslate.load_languages()
  682. for name in sorted(self.languages.values()):
  683. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  684. # #################################################################################
  685. # #################### DEFAULTS - PREFERENCES STORAGE #############################
  686. # #################################################################################
  687. self.defaults = LoudDict()
  688. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  689. self.defaults.update({
  690. # Global APP Preferences
  691. "first_run": True,
  692. "units": "IN",
  693. "global_serial": 0,
  694. "global_stats": {},
  695. "global_tabs_detachable": True,
  696. "global_graphic_engine": '3D',
  697. "global_app_level": 'b',
  698. "global_portable": False,
  699. "global_language": 'English',
  700. "global_version_check": True,
  701. "global_send_stats": True,
  702. "global_pan_button": '2',
  703. "global_mselect_key": 'Control',
  704. "global_project_at_startup": False,
  705. "global_systray_icon": True,
  706. "global_project_autohide": True,
  707. "global_toggle_tooltips": True,
  708. "global_worker_number": 2,
  709. "global_tolerance": 0.005,
  710. "global_open_style": True,
  711. "global_delete_confirmation": True,
  712. "global_compression_level": 3,
  713. "global_save_compressed": True,
  714. # Global GUI Preferences
  715. "global_gridx": 0.0393701,
  716. "global_gridy": 0.0393701,
  717. "global_snap_max": 0.001968504,
  718. "global_workspace": False,
  719. "global_workspaceT": "A4P",
  720. "global_grid_context_menu": {
  721. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  722. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  723. },
  724. "global_plot_fill": '#BBF268BF',
  725. "global_plot_line": '#006E20BF',
  726. "global_sel_fill": '#a5a5ffbf',
  727. "global_sel_line": '#0000ffbf',
  728. "global_alt_sel_fill": '#BBF268BF',
  729. "global_alt_sel_line": '#006E20BF',
  730. "global_draw_color": '#FF0000',
  731. "global_sel_draw_color": '#0000FF',
  732. "global_proj_item_color": '#000000',
  733. "global_proj_item_dis_color": '#b7b7cb',
  734. "global_activity_icon": 'Ball green',
  735. "global_toolbar_view": 511,
  736. "global_background_timeout": 300000, # Default value is 5 minutes
  737. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  738. # (python trace only for unknown errors),
  739. # 1 = show trace(show trace always),
  740. # 2 = (For the future).
  741. # Persistence
  742. "global_last_folder": None,
  743. "global_last_save_folder": None,
  744. # Default window geometry
  745. "global_def_win_x": 100,
  746. "global_def_win_y": 100,
  747. "global_def_win_w": 1024,
  748. "global_def_win_h": 650,
  749. "global_def_notebook_width": 1,
  750. # Constants...
  751. "global_defaults_save_period_ms": 20000, # Time between default saves.
  752. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  753. "global_shell_at_startup": False, # Show the shell at startup.
  754. "global_recent_limit": 10, # Max. items in recent list.
  755. "fit_key": 'V',
  756. "zoom_out_key": '-',
  757. "zoom_in_key": '=',
  758. "grid_toggle_key": 'G',
  759. "global_zoom_ratio": 1.5,
  760. "global_point_clipboard_format": "(%.4f, %.4f)",
  761. "global_zdownrate": None,
  762. # General GUI Settings
  763. "global_hover": False,
  764. "global_selection_shape": True,
  765. "global_layout": "compact",
  766. # Gerber General
  767. "gerber_plot": True,
  768. "gerber_solid": True,
  769. "gerber_multicolored": False,
  770. "gerber_circle_steps": 128,
  771. "gerber_use_buffer_for_union": True,
  772. # Gerber Options
  773. "gerber_isotooldia": 0.00787402,
  774. "gerber_isopasses": 1,
  775. "gerber_isooverlap": 0.00393701,
  776. "gerber_milling_type": "cl",
  777. "gerber_combine_passes": False,
  778. "gerber_noncoppermargin": 0.00393701,
  779. "gerber_noncopperrounded": False,
  780. "gerber_bboxmargin": 0.00393701,
  781. "gerber_bboxrounded": False,
  782. # Gerber Advanced Options
  783. "gerber_aperture_display": False,
  784. "gerber_aperture_scale_factor": 1.0,
  785. "gerber_aperture_buffer_factor": 0.0,
  786. "gerber_follow": False,
  787. "gerber_buffering": "full",
  788. "gerber_simplification": False,
  789. "gerber_simp_tolerance": 0.0005,
  790. # Gerber Export
  791. "gerber_exp_units": 'IN',
  792. "gerber_exp_integer": 2,
  793. "gerber_exp_decimals": 4,
  794. "gerber_exp_zeros": 'L',
  795. # Gerber Editor
  796. "gerber_editor_sel_limit": 30,
  797. "gerber_editor_newcode": 10,
  798. "gerber_editor_newsize": 0.8,
  799. "gerber_editor_newtype": 'C',
  800. "gerber_editor_newdim": "0.5, 0.5",
  801. "gerber_editor_array_size": 5,
  802. "gerber_editor_lin_axis": 'X',
  803. "gerber_editor_lin_pitch": 1,
  804. "gerber_editor_lin_angle": 0.0,
  805. "gerber_editor_circ_dir": 'CW',
  806. "gerber_editor_circ_angle": 0.0,
  807. "gerber_editor_scale_f": 1.0,
  808. "gerber_editor_buff_f": 0.1,
  809. "gerber_editor_ma_low": 0.0,
  810. "gerber_editor_ma_high": 1.0,
  811. # Excellon General
  812. "excellon_plot": True,
  813. "excellon_solid": True,
  814. "excellon_format_upper_in": 2,
  815. "excellon_format_lower_in": 4,
  816. "excellon_format_upper_mm": 3,
  817. "excellon_format_lower_mm": 3,
  818. "excellon_zeros": "L",
  819. "excellon_units": "INCH",
  820. "excellon_update": True,
  821. "excellon_optimization_type": 'B',
  822. "excellon_search_time": 3,
  823. # Excellon Options
  824. "excellon_drillz": -0.0590551,
  825. "excellon_travelz": 0.0787402,
  826. "excellon_endz": 0.5,
  827. "excellon_feedrate": 3.14961,
  828. "excellon_spindlespeed": None,
  829. "excellon_dwell": False,
  830. "excellon_dwelltime": 1,
  831. "excellon_toolchange": False,
  832. "excellon_toolchangez": 0.5,
  833. "excellon_ppname_e": 'default',
  834. "excellon_tooldia": 0.0314961,
  835. "excellon_slot_tooldia": 0.0708661,
  836. "excellon_gcode_type": "drills",
  837. # Excellon Advanced Options
  838. "excellon_offset": 0.0,
  839. "excellon_toolchangexy": "0.0, 0.0",
  840. "excellon_startz": None,
  841. "excellon_feedrate_rapid": 31.4961,
  842. "excellon_z_pdepth": -0.02,
  843. "excellon_feedrate_probe": 3.14961,
  844. "excellon_spindledir": 'CW',
  845. "excellon_f_plunge": False,
  846. "excellon_f_retract": False,
  847. # Excellon Export
  848. "excellon_exp_units": 'INCH',
  849. "excellon_exp_format": 'ndec',
  850. "excellon_exp_integer": 2,
  851. "excellon_exp_decimals": 4,
  852. "excellon_exp_zeros": 'LZ',
  853. "excellon_exp_slot_type": 'routing',
  854. # Excellon Editor
  855. "excellon_editor_sel_limit": 30,
  856. "excellon_editor_newdia": 0.039,
  857. "excellon_editor_array_size": 5,
  858. "excellon_editor_lin_dir": 'X',
  859. "excellon_editor_lin_pitch": 0.1,
  860. "excellon_editor_lin_angle": 0.0,
  861. "excellon_editor_circ_dir": 'CW',
  862. "excellon_editor_circ_angle": 12,
  863. # Excellon Slots
  864. "excellon_editor_slot_direction": 'X',
  865. "excellon_editor_slot_angle": 0.0,
  866. "excellon_editor_slot_length": 5.0,
  867. # Excellon Slot Array
  868. "excellon_editor_slot_array_size": 5,
  869. "excellon_editor_slot_lin_dir": 'X',
  870. "excellon_editor_slot_lin_pitch": 0.1,
  871. "excellon_editor_slot_lin_angle": 0.0,
  872. "excellon_editor_slot_circ_dir": 'CW',
  873. "excellon_editor_slot_circ_angle": 0.0,
  874. # Geometry General
  875. "geometry_plot": True,
  876. "geometry_circle_steps": 128,
  877. "geometry_cnctooldia": "0.0944882",
  878. # Geometry Options
  879. "geometry_cutz": -0.0944882,
  880. "geometry_vtipdia": 0.1,
  881. "geometry_vtipangle": 30,
  882. "geometry_multidepth": False,
  883. "geometry_depthperpass": 0.0314961,
  884. "geometry_travelz": 0.0787402,
  885. "geometry_toolchange": False,
  886. "geometry_toolchangez": 0.5,
  887. "geometry_endz": 0.5,
  888. "geometry_feedrate": 3.14961,
  889. "geometry_feedrate_z": 3.14961,
  890. "geometry_spindlespeed": None,
  891. "geometry_dwell": False,
  892. "geometry_dwelltime": 1,
  893. "geometry_ppname_g": 'default',
  894. # Geometry Advanced Options
  895. "geometry_toolchangexy": "0.0, 0.0",
  896. "geometry_startz": None,
  897. "geometry_feedrate_rapid": 3.14961,
  898. "geometry_extracut": False,
  899. "geometry_z_pdepth": -0.02,
  900. "geometry_f_plunge": False,
  901. "geometry_spindledir": 'CW',
  902. "geometry_feedrate_probe": 3.14961,
  903. "geometry_segx": 0.0,
  904. "geometry_segy": 0.0,
  905. # Geometry Editor
  906. "geometry_editor_sel_limit": 30,
  907. # CNC Job General
  908. "cncjob_plot": True,
  909. "cncjob_plot_kind": 'all',
  910. "cncjob_annotation": True,
  911. "cncjob_tooldia": 0.0393701,
  912. "cncjob_coords_type": "G90",
  913. "cncjob_coords_decimals": 4,
  914. "cncjob_fr_decimals": 2,
  915. "cncjob_steps_per_circle": 128,
  916. # CNC Job Options
  917. "cncjob_prepend": "",
  918. "cncjob_append": "",
  919. # CNC Job Advanced Options
  920. "cncjob_toolchange_macro": "",
  921. "cncjob_toolchange_macro_enable": False,
  922. "cncjob_annotation_fontsize": 9,
  923. "cncjob_annotation_fontcolor": '#990000',
  924. # NCC Tool
  925. "tools_ncctools": "0.0393701, 0.019685",
  926. "tools_nccorder": 'rev',
  927. "tools_nccoverlap": 0.015748,
  928. "tools_nccmargin": 0.0393701,
  929. "tools_nccmethod": "seed",
  930. "tools_nccconnect": True,
  931. "tools_ncccontour": True,
  932. "tools_nccrest": False,
  933. "tools_ncc_offset_choice": False,
  934. "tools_ncc_offset_value": 0.0000,
  935. "tools_nccref": 'itself',
  936. "tools_ncc_plotting": 'normal',
  937. "tools_nccmilling_type": 'cl',
  938. "tools_ncctool_type": 'V',
  939. "tools_ncccutz": -0.001968504,
  940. "tools_ncctipdia": 0.00393701,
  941. "tools_ncctipangle": 30,
  942. # Cutout Tool
  943. "tools_cutouttooldia": 0.0944882,
  944. "tools_cutoutkind": "single",
  945. "tools_cutoutmargin": 0.00393701,
  946. "tools_cutoutgapsize": 0.15748,
  947. "tools_gaps_ff": "4",
  948. "tools_cutout_convexshape": False,
  949. # Paint Tool
  950. "tools_painttooldia": 0.023622,
  951. "tools_paintorder": 'rev',
  952. "tools_paintoverlap": 0.015748,
  953. "tools_paintmargin": 0.0,
  954. "tools_paintmethod": "seed",
  955. "tools_selectmethod": "all",
  956. "tools_pathconnect": True,
  957. "tools_paintcontour": True,
  958. "tools_paint_plotting": 'normal',
  959. # 2-Sided Tool
  960. "tools_2sided_mirror_axis": "X",
  961. "tools_2sided_axis_loc": "point",
  962. "tools_2sided_drilldia": 0.11811,
  963. # Film Tool
  964. "tools_film_type": 'neg',
  965. "tools_film_boundary": 0.0393701,
  966. "tools_film_scale": 0,
  967. "tools_film_color": '#000000',
  968. # Panel Tool
  969. "tools_panelize_spacing_columns": 0,
  970. "tools_panelize_spacing_rows": 0,
  971. "tools_panelize_columns": 1,
  972. "tools_panelize_rows": 1,
  973. "tools_panelize_constrain": False,
  974. "tools_panelize_constrainx": 0.0,
  975. "tools_panelize_constrainy": 0.0,
  976. "tools_panelize_panel_type": 'gerber',
  977. # Calculators Tool
  978. "tools_calc_vshape_tip_dia": 0.007874,
  979. "tools_calc_vshape_tip_angle": 30,
  980. "tools_calc_vshape_cut_z": 0.000787,
  981. "tools_calc_electro_length": 10.0,
  982. "tools_calc_electro_width": 10.0,
  983. "tools_calc_electro_cdensity": 13.0,
  984. "tools_calc_electro_growth": 10.0,
  985. # Transform Tool
  986. "tools_transform_rotate": 90,
  987. "tools_transform_skew_x": 0.0,
  988. "tools_transform_skew_y": 0.0,
  989. "tools_transform_scale_x": 1.0,
  990. "tools_transform_scale_y": 1.0,
  991. "tools_transform_scale_link": True,
  992. "tools_transform_scale_reference": True,
  993. "tools_transform_offset_x": 0.0,
  994. "tools_transform_offset_y": 0.0,
  995. "tools_transform_mirror_reference": False,
  996. "tools_transform_mirror_point": (0, 0),
  997. # SolderPaste Tool
  998. "tools_solderpaste_tools": "0.0393701, 0.011811",
  999. "tools_solderpaste_new": 0.011811,
  1000. "tools_solderpaste_z_start": 0.00019685039,
  1001. "tools_solderpaste_z_dispense": 0.00393701,
  1002. "tools_solderpaste_z_stop": 0.00019685039,
  1003. "tools_solderpaste_z_travel": 0.00393701,
  1004. "tools_solderpaste_z_toolchange": 0.0393701,
  1005. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  1006. "tools_solderpaste_frxy": 3.0,
  1007. "tools_solderpaste_frz": 3.0,
  1008. "tools_solderpaste_frz_dispense": 0.0393701,
  1009. "tools_solderpaste_speedfwd": 20,
  1010. "tools_solderpaste_dwellfwd": 1,
  1011. "tools_solderpaste_speedrev": 10,
  1012. "tools_solderpaste_dwellrev": 1,
  1013. "tools_solderpaste_pp": 'Paste_1',
  1014. # Subtract Tool
  1015. "tools_sub_close_paths": True,
  1016. # Utilities
  1017. # file associations
  1018. "fa_excellon": 'drd, drl, exc, ncd, tap, xln',
  1019. "fa_gcode": 'cnc, din, dnc, ecs, eia, fan, fgc, fnc, gc, gcd, gcode, h, hnc, i, min, mpf, mpr, nc, ncc, '
  1020. 'ncg, ncp, out, plt, ply, rol, sbp, tap, xpi',
  1021. "fa_gerber": 'art, bot, bsm, cmp, crc, crs, dim, g4, gb0, gb1, gb2, gb3, gb5, gb6, gb7, gb8, gb9, gbd, '
  1022. 'gbl, gbo, gbp, gbr, gbs, gdo, ger, gko, gm1, gm2, gm3, grb, gtl, gto, gtp, gts, ly15, ly2, '
  1023. 'mil, pho, plc, pls, smb, smt, sol, spb, spt, ssb, sst, stc, sts, top, tsm',
  1024. # Keyword list
  1025. "util_autocomplete_keywords": 'Desktop, Documents, FlatConfig, FlatPrj, Marius, My Documents, Paste_1, '
  1026. 'Repetier, Roland_MDX_20, Toolchange_Custom, Toolchange_Probe_MACH3, '
  1027. 'Toolchange_manual, Users, all, angle_x, angle_y, axis, axisoffset, box, '
  1028. 'center_x, center_y, columns, combine, connect, contour, default, '
  1029. 'depthperpass, dia, diatol, dist, drilled_dias, drillz, dwell, dwelltime, '
  1030. 'feedrate_z, grbl_11, grbl_laser, gridoffsety, gridx, gridy, has_offset, '
  1031. 'holes, hpgl, iso_type, line_xyz, margin, marlin, method, milled_dias, '
  1032. 'minoffset, multidepth, name, offset, opt_type, order, outname, overlap, '
  1033. 'passes, postamble, pp, ppname_e, ppname_g, preamble, radius, ref, rest, '
  1034. 'rows, shellvar_, scale_factor, spacing_columns, spacing_rows, spindlespeed, '
  1035. 'toolchange_xy, use_threads, value, x, x0, x1, y, y0, y1, z_cut, z_move'
  1036. ,
  1037. })
  1038. # ############################################################
  1039. # ############### Load defaults from file ####################
  1040. # ############################################################
  1041. if user_defaults:
  1042. self.load_defaults(filename='current_defaults')
  1043. # #############################################################
  1044. # ############## APPLY APP LANGUAGE ###########################
  1045. # #############################################################
  1046. ret_val = fcTranslate.apply_language('strings')
  1047. if ret_val == "no language":
  1048. self.inform.emit('[ERROR] %s' %
  1049. _("Could not find the Language files. The App strings are missing."))
  1050. log.debug("Could not find the Language files. The App strings are missing.")
  1051. else:
  1052. # make the current language the current selection on the language combobox
  1053. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  1054. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  1055. # ##############################################################
  1056. # ################# CREATE UNIQUE SERIAL NUMBER ################
  1057. # ##############################################################
  1058. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  1059. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  1060. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  1061. self.save_defaults(silent=True, first_time=True)
  1062. self.propagate_defaults(silent=True)
  1063. self.restore_main_win_geom()
  1064. # def auto_save_defaults():
  1065. # try:
  1066. # self.save_defaults(silent=True)
  1067. # self.propagate_defaults(silent=True)
  1068. # finally:
  1069. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1070. # the following lines activates automatic defaults save
  1071. # if user_defaults:
  1072. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1073. # self.options_form = PreferencesUI()
  1074. self.options_form_fields = {
  1075. "units": self.ui.general_options_form.general_app_group.units_radio,
  1076. "global_gridx": self.ui.general_options_form.general_gui_group.gridx_entry,
  1077. "global_gridy": self.ui.general_options_form.general_gui_group.gridy_entry,
  1078. "global_snap_max": self.ui.general_options_form.general_gui_group.snap_max_dist_entry,
  1079. "gerber_plot": self.ui.gerber_options_form.gerber_gen_group.plot_cb,
  1080. "gerber_solid": self.ui.gerber_options_form.gerber_gen_group.solid_cb,
  1081. "gerber_multicolored": self.ui.gerber_options_form.gerber_gen_group.multicolored_cb,
  1082. "gerber_isotooldia": self.ui.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  1083. "gerber_isopasses": self.ui.gerber_options_form.gerber_opt_group.iso_width_entry,
  1084. "gerber_isooverlap": self.ui.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  1085. "gerber_combine_passes": self.ui.gerber_options_form.gerber_opt_group.combine_passes_cb,
  1086. "gerber_noncoppermargin": self.ui.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  1087. "gerber_noncopperrounded": self.ui.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  1088. "gerber_bboxmargin": self.ui.gerber_options_form.gerber_opt_group.bbmargin_entry,
  1089. "gerber_bboxrounded": self.ui.gerber_options_form.gerber_opt_group.bbrounded_cb,
  1090. "excellon_plot": self.ui.excellon_options_form.excellon_gen_group.plot_cb,
  1091. "excellon_solid": self.ui.excellon_options_form.excellon_gen_group.solid_cb,
  1092. "excellon_format_upper_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  1093. "excellon_format_lower_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  1094. "excellon_format_upper_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  1095. "excellon_format_lower_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  1096. "excellon_zeros": self.ui.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  1097. "excellon_units": self.ui.excellon_options_form.excellon_gen_group.excellon_units_radio,
  1098. "excellon_optimization_type": self.ui.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  1099. "excellon_drillz": self.ui.excellon_options_form.excellon_opt_group.cutz_entry,
  1100. "excellon_travelz": self.ui.excellon_options_form.excellon_opt_group.travelz_entry,
  1101. "excellon_endz": self.ui.excellon_options_form.excellon_opt_group.eendz_entry,
  1102. "excellon_feedrate": self.ui.excellon_options_form.excellon_opt_group.feedrate_entry,
  1103. "excellon_spindlespeed": self.ui.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  1104. "excellon_dwell": self.ui.excellon_options_form.excellon_opt_group.dwell_cb,
  1105. "excellon_dwelltime": self.ui.excellon_options_form.excellon_opt_group.dwelltime_entry,
  1106. "excellon_toolchange": self.ui.excellon_options_form.excellon_opt_group.toolchange_cb,
  1107. "excellon_toolchangez": self.ui.excellon_options_form.excellon_opt_group.toolchangez_entry,
  1108. "excellon_tooldia": self.ui.excellon_options_form.excellon_opt_group.tooldia_entry,
  1109. "excellon_ppname_e": self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  1110. "excellon_feedrate_rapid": self.ui.excellon_options_form.excellon_adv_opt_group.feedrate_rapid_entry,
  1111. "excellon_toolchangexy": self.ui.excellon_options_form.excellon_adv_opt_group.toolchangexy_entry,
  1112. "excellon_f_plunge": self.ui.excellon_options_form.excellon_adv_opt_group.fplunge_cb,
  1113. "excellon_startz": self.ui.excellon_options_form.excellon_adv_opt_group.estartz_entry,
  1114. "excellon_spindledir": self.ui.excellon_options_form.excellon_adv_opt_group.spindledir_radio,
  1115. "geometry_plot": self.ui.geometry_options_form.geometry_gen_group.plot_cb,
  1116. "geometry_cnctooldia": self.ui.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  1117. "geometry_cutz": self.ui.geometry_options_form.geometry_opt_group.cutz_entry,
  1118. "geometry_travelz": self.ui.geometry_options_form.geometry_opt_group.travelz_entry,
  1119. "geometry_feedrate": self.ui.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  1120. "geometry_feedrate_z": self.ui.geometry_options_form.geometry_opt_group.cncplunge_entry,
  1121. "geometry_spindlespeed": self.ui.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  1122. "geometry_dwell": self.ui.geometry_options_form.geometry_opt_group.dwell_cb,
  1123. "geometry_dwelltime": self.ui.geometry_options_form.geometry_opt_group.dwelltime_entry,
  1124. "geometry_ppname_g": self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  1125. "geometry_toolchange": self.ui.geometry_options_form.geometry_opt_group.toolchange_cb,
  1126. "geometry_toolchangez": self.ui.geometry_options_form.geometry_opt_group.toolchangez_entry,
  1127. "geometry_endz": self.ui.geometry_options_form.geometry_opt_group.gendz_entry,
  1128. "geometry_depthperpass": self.ui.geometry_options_form.geometry_opt_group.depthperpass_entry,
  1129. "geometry_multidepth": self.ui.geometry_options_form.geometry_opt_group.multidepth_cb,
  1130. "geometry_segx": self.ui.geometry_options_form.geometry_adv_opt_group.segx_entry,
  1131. "geometry_segy": self.ui.geometry_options_form.geometry_adv_opt_group.segy_entry,
  1132. "geometry_feedrate_rapid": self.ui.geometry_options_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  1133. "geometry_f_plunge": self.ui.geometry_options_form.geometry_adv_opt_group.fplunge_cb,
  1134. "geometry_spindledir": self.ui.geometry_options_form.geometry_adv_opt_group.spindledir_radio,
  1135. "geometry_toolchangexy": self.ui.geometry_options_form.geometry_adv_opt_group.toolchangexy_entry,
  1136. "geometry_startz": self.ui.geometry_options_form.geometry_adv_opt_group.gstartz_entry,
  1137. "geometry_extracut": self.ui.geometry_options_form.geometry_adv_opt_group.extracut_cb,
  1138. "cncjob_plot": self.ui.cncjob_options_form.cncjob_gen_group.plot_cb,
  1139. "cncjob_tooldia": self.ui.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  1140. "cncjob_prepend": self.ui.cncjob_options_form.cncjob_opt_group.prepend_text,
  1141. "cncjob_append": self.ui.cncjob_options_form.cncjob_opt_group.append_text,
  1142. "tools_ncctools": self.ui.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  1143. "tools_nccoverlap": self.ui.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  1144. "tools_nccmargin": self.ui.tools_options_form.tools_ncc_group.ncc_margin_entry,
  1145. "tools_cutouttooldia": self.ui.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  1146. "tools_cutoutmargin": self.ui.tools_options_form.tools_cutout_group.cutout_margin_entry,
  1147. "tools_cutoutgapsize": self.ui.tools_options_form.tools_cutout_group.cutout_gap_entry,
  1148. "tools_gaps_ff": self.ui.tools_options_form.tools_cutout_group.gaps_combo,
  1149. "tools_painttooldia": self.ui.tools_options_form.tools_paint_group.painttooldia_entry,
  1150. "tools_paintoverlap": self.ui.tools_options_form.tools_paint_group.paintoverlap_entry,
  1151. "tools_paintmargin": self.ui.tools_options_form.tools_paint_group.paintmargin_entry,
  1152. "tools_paintmethod": self.ui.tools_options_form.tools_paint_group.paintmethod_combo,
  1153. "tools_selectmethod": self.ui.tools_options_form.tools_paint_group.selectmethod_combo,
  1154. "tools_pathconnect": self.ui.tools_options_form.tools_paint_group.pathconnect_cb,
  1155. "tools_paintcontour": self.ui.tools_options_form.tools_paint_group.contour_cb,
  1156. "tools_2sided_mirror_axis": self.ui.tools_options_form.tools_2sided_group.mirror_axis_radio,
  1157. "tools_2sided_axis_loc": self.ui.tools_options_form.tools_2sided_group.axis_location_radio,
  1158. "tools_2sided_drilldia": self.ui.tools_options_form.tools_2sided_group.drill_dia_entry,
  1159. "tools_film_type": self.ui.tools_options_form.tools_film_group.film_type_radio,
  1160. "tools_film_boundary": self.ui.tools_options_form.tools_film_group.film_boundary_entry,
  1161. "tools_film_scale": self.ui.tools_options_form.tools_film_group.film_scale_entry,
  1162. "tools_panelize_spacing_columns": self.ui.tools_options_form.tools_panelize_group.pspacing_columns,
  1163. "tools_panelize_spacing_rows": self.ui.tools_options_form.tools_panelize_group.pspacing_rows,
  1164. "tools_panelize_columns": self.ui.tools_options_form.tools_panelize_group.pcolumns,
  1165. "tools_panelize_rows": self.ui.tools_options_form.tools_panelize_group.prows,
  1166. "tools_panelize_constrain": self.ui.tools_options_form.tools_panelize_group.pconstrain_cb,
  1167. "tools_panelize_constrainx": self.ui.tools_options_form.tools_panelize_group.px_width_entry,
  1168. "tools_panelize_constrainy": self.ui.tools_options_form.tools_panelize_group.py_height_entry
  1169. }
  1170. for name in list(self.postprocessors.keys()):
  1171. self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1172. self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1173. self.options = LoudDict()
  1174. self.options.set_change_callback(self.on_options_dict_change)
  1175. self.options.update({
  1176. "units": "IN",
  1177. "global_gridx": 1.0,
  1178. "global_gridy": 1.0,
  1179. "global_snap_max": 0.05,
  1180. "global_background_timeout": 300000, # Default value is 5 minutes
  1181. "global_verbose_error_level": 0, # Shell verbosity:
  1182. # 0 = default(python trace only for unknown errors),
  1183. # 1 = show trace(show trace allways), 2 = (For the future).
  1184. "gerber_plot": True,
  1185. "gerber_solid": True,
  1186. "gerber_multicolored": False,
  1187. "gerber_isotooldia": 0.016,
  1188. "gerber_isopasses": 1,
  1189. "gerber_isooverlap": 0.15,
  1190. "gerber_combine_passes": True,
  1191. "gerber_noncoppermargin": 0.0,
  1192. "gerber_noncopperrounded": False,
  1193. "gerber_bboxmargin": 0.0,
  1194. "gerber_bboxrounded": False,
  1195. "excellon_plot": True,
  1196. "excellon_solid": False,
  1197. "excellon_format_upper_in": 2,
  1198. "excellon_format_lower_in": 4,
  1199. "excellon_format_upper_mm": 3,
  1200. "excellon_format_lower_mm": 3,
  1201. "excellon_units": 'INCH',
  1202. "excellon_optimization_type": 'B',
  1203. "excellon_search_time": 3,
  1204. "excellon_zeros": "L",
  1205. "excellon_drillz": -0.1,
  1206. "excellon_travelz": 0.1,
  1207. "excellon_feedrate": 3.0,
  1208. "excellon_feedrate_rapid": 3.0,
  1209. "excellon_spindlespeed": None,
  1210. "excellon_spindledir": 'CW',
  1211. "excellon_dwell": True,
  1212. "excellon_dwelltime": 1000,
  1213. "excellon_toolchange": False,
  1214. "excellon_toolchangez": 1.0,
  1215. "excellon_toolchangexy": "0.0, 0.0",
  1216. "excellon_tooldia": 0.016,
  1217. "excellon_ppname_e": 'default',
  1218. "excellon_f_plunge": False,
  1219. "excellon_startz": None,
  1220. "excellon_endz": 2.0,
  1221. "geometry_plot": True,
  1222. "geometry_segx": 0.0,
  1223. "geometry_segy": 0.0,
  1224. "geometry_cutz": -0.002,
  1225. "geometry_vtipdia": 0.1,
  1226. "geometry_vtipangle": 30,
  1227. "geometry_travelz": 0.1,
  1228. "geometry_feedrate": 3.0,
  1229. "geometry_feedrate_z": 3.0,
  1230. "geometry_feedrate_rapid": 3.0,
  1231. "geometry_spindlespeed": None,
  1232. "geometry_spindledir": 'CW',
  1233. "geometry_dwell": True,
  1234. "geometry_dwelltime": 1000,
  1235. "geometry_cnctooldia": 0.016,
  1236. "geometry_toolchange": False,
  1237. "geometry_toolchangez": 2.0,
  1238. "geometry_toolchangexy": "0.0, 0.0",
  1239. "geometry_startz": None,
  1240. "geometry_endz": 2.0,
  1241. "geometry_ppname_g": "default",
  1242. "geometry_f_plunge": False,
  1243. "geometry_depthperpass": 0.002,
  1244. "geometry_multidepth": False,
  1245. "geometry_extracut": False,
  1246. "cncjob_plot": True,
  1247. "cncjob_tooldia": 0.016,
  1248. "cncjob_prepend": "",
  1249. "cncjob_append": "",
  1250. "tools_ncctools": "1.0, 0.5",
  1251. "tools_nccoverlap": 0.4,
  1252. "tools_nccmargin": 1,
  1253. "tools_cutouttooldia": 0.07,
  1254. "tools_cutoutmargin": 0.1,
  1255. "tools_cutoutgapsize": 0.15,
  1256. "tools_gaps_ff": "8",
  1257. "tools_painttooldia": 0.07,
  1258. "tools_paintoverlap": 0.15,
  1259. "tools_paintmargin": 0.0,
  1260. "tools_paintmethod": "seed",
  1261. "tools_selectmethod": "single",
  1262. "tools_pathconnect": True,
  1263. "tools_paintcontour": True,
  1264. "tools_2sided_mirror_axis": "X",
  1265. "tools_2sided_axis_loc": 'point',
  1266. "tools_2sided_drilldia": 1,
  1267. "tools_film_type": 'neg',
  1268. "tools_film_boundary": 1,
  1269. "tools_film_scale": 0,
  1270. "tools_panelize_spacing_columns": 0,
  1271. "tools_panelize_spacing_rows": 0,
  1272. "tools_panelize_columns": 1,
  1273. "tools_panelize_rows": 1,
  1274. "tools_panelize_constrain": False,
  1275. "tools_panelize_constrainx": 0.0,
  1276. "tools_panelize_constrainy": 0.0
  1277. })
  1278. self.options.update(self.defaults) # Copy app defaults to project options
  1279. self.gen_form = None
  1280. self.ger_form = None
  1281. self.exc_form = None
  1282. self.geo_form = None
  1283. self.cnc_form = None
  1284. self.tools_form = None
  1285. self.fa_form = None
  1286. self.on_options_combo_change(0) # Will show the initial form
  1287. # ################################
  1288. # ### Initialize the color box's color in Preferences -> Global -> Color
  1289. # Init Plot Colors
  1290. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  1291. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  1292. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  1293. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  1294. int(self.defaults['global_plot_fill'][7:9], 16))
  1295. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  1296. int(self.defaults['global_plot_fill'][7:9], 16))
  1297. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  1298. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  1299. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  1300. # Init Left-Right Selection colors
  1301. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  1302. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  1303. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  1304. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  1305. int(self.defaults['global_sel_fill'][7:9], 16))
  1306. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  1307. int(self.defaults['global_sel_fill'][7:9], 16))
  1308. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  1309. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  1310. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  1311. # Init Right-Left Selection colors
  1312. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  1313. self.defaults['global_alt_sel_fill'])
  1314. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  1315. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  1316. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  1317. int(self.defaults['global_sel_fill'][7:9], 16))
  1318. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  1319. int(self.defaults['global_sel_fill'][7:9], 16))
  1320. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  1321. self.defaults['global_alt_sel_line'])
  1322. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  1323. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  1324. # Init Draw color and Selection Draw Color
  1325. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  1326. self.defaults['global_draw_color'])
  1327. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  1328. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  1329. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  1330. self.defaults['global_sel_draw_color'])
  1331. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  1332. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  1333. # Init Project Items color
  1334. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  1335. self.defaults['global_proj_item_color'])
  1336. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  1337. "background-color:%s" % str(self.defaults['global_proj_item_color'])[:7])
  1338. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  1339. self.defaults['global_proj_item_dis_color'])
  1340. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  1341. "background-color:%s" % str(self.defaults['global_proj_item_dis_color'])[:7])
  1342. # Init the Annotation CNC Job color
  1343. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(
  1344. self.defaults['cncjob_annotation_fontcolor'])
  1345. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  1346. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  1347. # Init the Tool Film color
  1348. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(
  1349. self.defaults['tools_film_color'])
  1350. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  1351. "background-color:%s" % str(self.defaults['tools_film_color'])[:7])
  1352. # ### End of Data ####
  1353. # ###############################################
  1354. # ############# SETUP Plot Area #################
  1355. # ###############################################
  1356. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  1357. if self.defaults["global_graphic_engine"] == '3D':
  1358. self.is_legacy = False
  1359. else:
  1360. self.is_legacy = True
  1361. # Matplotlib axis
  1362. self.axes = None
  1363. if show_splash:
  1364. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  1365. "Canvas initialization started."),
  1366. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1367. color=QtGui.QColor("gray"))
  1368. start_plot_time = time.time() # debug
  1369. self.plotcanvas = None
  1370. self.app_cursor = None
  1371. self.hover_shapes = None
  1372. self.on_plotcanvas_setup()
  1373. end_plot_time = time.time()
  1374. self.used_time = end_plot_time - start_plot_time
  1375. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  1376. if show_splash:
  1377. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  1378. "Canvas initialization started.\n"
  1379. "Canvas initialization finished in"), '%.2f' % self.used_time),
  1380. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1381. color=QtGui.QColor("gray"))
  1382. self.ui.splitter.setStretchFactor(1, 2)
  1383. # #################################################################
  1384. # ####################### SYS TRAY ################################
  1385. # #################################################################
  1386. if self.defaults["global_systray_icon"]:
  1387. self.parent_w = QtWidgets.QWidget()
  1388. if self.cmd_line_headless == 1:
  1389. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1390. headless=True,
  1391. parent=self.parent_w)
  1392. else:
  1393. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1394. parent=self.parent_w)
  1395. # ##############################################
  1396. # ######### SETUP OBJECT COLLECTION ############
  1397. # ##############################################
  1398. self.collection = ObjectCollection(self)
  1399. self.ui.project_tab_layout.addWidget(self.collection.view)
  1400. # ### Adjust tabs width ## ##
  1401. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1402. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1403. self.collection.view.setMinimumWidth(290)
  1404. self.log.debug("Finished creating Object Collection.")
  1405. # ###############################################
  1406. # ############# Worker SETUP ####################
  1407. # ###############################################
  1408. if self.defaults["global_worker_number"]:
  1409. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1410. else:
  1411. self.workers = WorkerStack(workers_number=2)
  1412. self.worker_task.connect(self.workers.add_task)
  1413. self.log.debug("Finished creating Workers crew.")
  1414. # ################################################
  1415. # ############### Activity Monitor ###############
  1416. # ################################################
  1417. if self.defaults["global_activity_icon"] == "Ball green":
  1418. icon = 'share/active_2_static.png'
  1419. movie = "share/active_2.gif"
  1420. elif self.defaults["global_activity_icon"] == "Ball black":
  1421. icon = 'share/active_static.png'
  1422. movie = "share/active.gif"
  1423. elif self.defaults["global_activity_icon"] == "Arrow green":
  1424. icon = 'share/active_3_static.png'
  1425. movie = "share/active_3.gif"
  1426. elif self.defaults["global_activity_icon"] == "Eclipse green":
  1427. icon = 'share/active_4_static.png'
  1428. movie = "share/active_4.gif"
  1429. else:
  1430. icon = 'share/active_static.png'
  1431. movie = "share/active.gif"
  1432. self.activity_view = FlatCAMActivityView(icon=icon, movie=movie)
  1433. self.ui.infobar.addWidget(self.activity_view)
  1434. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  1435. # ################################################
  1436. # ############### Signal handling ################
  1437. # ################################################
  1438. # ############# Custom signals ##################
  1439. # signal for displaying messages in status bar
  1440. self.inform.connect(self.info)
  1441. # signal to be called when the app is quiting
  1442. self.app_quit.connect(self.quit_application)
  1443. self.message.connect(self.message_dialog)
  1444. self.progress.connect(self.set_progress_bar)
  1445. # signals that are emitted when object state changes
  1446. self.object_created.connect(self.on_object_created)
  1447. self.object_changed.connect(self.on_object_changed)
  1448. self.object_plotted.connect(self.on_object_plotted)
  1449. self.plots_updated.connect(self.on_plots_updated)
  1450. # signals emitted when file state change
  1451. self.file_opened.connect(self.register_recent)
  1452. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1453. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1454. # ############# Standard signals ###################
  1455. # ### Menu
  1456. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1457. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1458. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1459. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1460. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1461. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1462. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1463. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1464. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1465. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1466. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1467. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1468. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1469. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1470. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1471. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1472. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1473. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1474. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1475. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1476. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1477. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1478. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1479. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1480. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1481. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1482. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1483. self.ui.menufile_exit.triggered.connect(self.final_save)
  1484. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1485. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1486. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1487. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1488. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1489. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1490. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1491. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1492. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1493. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1494. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1495. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1496. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1497. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1498. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1499. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1500. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1501. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1502. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1503. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1504. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1505. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1506. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1507. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1508. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1509. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1510. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1511. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1512. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1513. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1514. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1515. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1516. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1517. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1518. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1519. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1520. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1521. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1522. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1523. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1524. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1525. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1526. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1527. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1528. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  1529. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1530. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1531. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1532. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1533. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1534. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1535. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1536. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1537. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1538. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1539. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1540. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1541. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1542. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1543. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1544. # ToolBar signals
  1545. self.connect_toolbar_signals()
  1546. # Notebook signals
  1547. # make the right click on the notebook tab connect to a function
  1548. self.ui.notebook.setupContextMenu()
  1549. self.ui.notebook.addContextMenu(
  1550. _("Detachable Tabs"), self.on_notebook_tab_rmb_click,
  1551. initial_checked=self.defaults["global_tabs_detachable"])
  1552. # activate initial state
  1553. self.on_notebook_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1554. # Context Menu
  1555. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1556. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1557. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1558. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1559. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1560. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1561. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1562. self.ui.clearplot.triggered.connect(self.clear_plots)
  1563. self.ui.replot.triggered.connect(self.plot_all)
  1564. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1565. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1566. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1567. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1568. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1569. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1570. # Preferences Plot Area TAB
  1571. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1572. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1573. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1574. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1575. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1576. # ##############################
  1577. # ### GUI PREFERENCES SIGNALS ##
  1578. # ##############################
  1579. self.ui.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1580. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1581. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1582. )
  1583. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1584. lambda: self.on_toggle_units(no_pref=False))
  1585. # ###############################################################
  1586. # ################### GUI COLORS SIGNALS ########################
  1587. # ###############################################################
  1588. # Setting plot colors signals
  1589. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1590. self.on_pf_color_entry)
  1591. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1592. self.on_pf_color_button)
  1593. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1594. self.on_pf_color_spinner)
  1595. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1596. self.on_pf_color_slider)
  1597. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1598. self.on_pl_color_entry)
  1599. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1600. self.on_pl_color_button)
  1601. # Setting selection (left - right) colors signals
  1602. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1603. self.on_sf_color_entry)
  1604. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1605. self.on_sf_color_button)
  1606. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1607. self.on_sf_color_spinner)
  1608. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1609. self.on_sf_color_slider)
  1610. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1611. self.on_sl_color_entry)
  1612. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1613. self.on_sl_color_button)
  1614. # Setting selection (right - left) colors signals
  1615. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1616. self.on_alt_sf_color_entry)
  1617. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1618. self.on_alt_sf_color_button)
  1619. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1620. self.on_alt_sf_color_spinner)
  1621. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1622. self.on_alt_sf_color_slider)
  1623. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1624. self.on_alt_sl_color_entry)
  1625. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1626. self.on_alt_sl_color_button)
  1627. # Setting Editor Draw colors signals
  1628. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1629. self.on_draw_color_entry)
  1630. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1631. self.on_draw_color_button)
  1632. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1633. self.on_sel_draw_color_entry)
  1634. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1635. self.on_sel_draw_color_button)
  1636. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1637. self.on_proj_color_entry)
  1638. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1639. self.on_proj_color_button)
  1640. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1641. self.on_proj_color_dis_entry)
  1642. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1643. self.on_proj_color_dis_button)
  1644. # ########## workspace setting signals ###########
  1645. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1646. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1647. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1648. # ########## CNC Job related signals #############
  1649. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1650. self.on_cnc_custom_parameters)
  1651. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.editingFinished.connect(
  1652. self.on_annotation_fontcolor_entry)
  1653. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.clicked.connect(
  1654. self.on_annotation_fontcolor_button)
  1655. # ########## Tools related signals #############
  1656. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  1657. self.on_film_color_entry)
  1658. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  1659. self.on_film_color_button)
  1660. # ########## Modify G-CODE Plot Area TAB ###########
  1661. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  1662. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  1663. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  1664. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  1665. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  1666. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  1667. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  1668. # portability changed signal
  1669. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1670. # Object list
  1671. self.collection.view.activated.connect(self.on_row_activated)
  1672. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1673. self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1674. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  1675. # Export Excellon parameters.
  1676. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  1677. self.on_update_exc_export
  1678. )
  1679. # call it once to make sure it is updated at startup
  1680. self.on_update_exc_export(state=self.defaults["excellon_update"])
  1681. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1682. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1683. self.on_excellon_defaults_button)
  1684. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1685. self.ui.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1686. self.on_excellon_options_button)
  1687. # when there are arguments at application startup this get launched
  1688. self.args_at_startup[list].connect(self.on_startup_args)
  1689. # ##############################################################
  1690. # ############### FILE ASSOCIATIONS SIGNALS ####################
  1691. # ##############################################################
  1692. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1693. lambda: self.restore_extensions(ext_type='excellon'))
  1694. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1695. lambda: self.restore_extensions(ext_type='gcode'))
  1696. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1697. lambda: self.restore_extensions(ext_type='gerber'))
  1698. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1699. lambda: self.delete_all_extensions(ext_type='excellon'))
  1700. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1701. lambda: self.delete_all_extensions(ext_type='gcode'))
  1702. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1703. lambda: self.delete_all_extensions(ext_type='gerber'))
  1704. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1705. lambda: self.add_extension(ext_type='excellon'))
  1706. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1707. lambda: self.add_extension(ext_type='gcode'))
  1708. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1709. lambda: self.add_extension(ext_type='gerber'))
  1710. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1711. lambda: self.del_extension(ext_type='excellon'))
  1712. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1713. lambda: self.del_extension(ext_type='gcode'))
  1714. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1715. lambda: self.del_extension(ext_type='gerber'))
  1716. # connect the 'Apply' buttons from the Preferences/File Associations
  1717. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1718. lambda: self.on_register_files(obj_type='excellon'))
  1719. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1720. lambda: self.on_register_files(obj_type='gcode'))
  1721. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1722. lambda: self.on_register_files(obj_type='gerber'))
  1723. # ##############################################################
  1724. # ###################### KEYWORDS SIGNALS ######################
  1725. # ##############################################################
  1726. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1727. lambda: self.restore_extensions(ext_type='keyword'))
  1728. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1729. lambda: self.delete_all_extensions(ext_type='keyword'))
  1730. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1731. lambda: self.add_extension(ext_type='keyword'))
  1732. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1733. lambda: self.del_extension(ext_type='keyword'))
  1734. # splash screen button signal
  1735. self.ui.general_defaults_form.general_gui_set_group.splash_cb.stateChanged.connect(self.on_splash_changed)
  1736. # connect the abort_all_tasks related slots to the related signals
  1737. self.proc_container.idle_flag.connect(self.app_is_idle)
  1738. # #####################################################################################
  1739. # ########### FINISHED CONNECTING SIGNALS #############################################
  1740. # #####################################################################################
  1741. self.log.debug("Finished connecting Signals.")
  1742. # #####################################################################################
  1743. # ########################## Other setups #############################################
  1744. # #####################################################################################
  1745. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  1746. # depending on from where those tools are called different actions can be done
  1747. self.call_source = 'app'
  1748. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1749. self.tool_tab_locked = False
  1750. # decide if to show or hide the Notebook side of the screen at startup
  1751. if self.defaults["global_project_at_startup"] is True:
  1752. self.ui.splitter.setSizes([1, 1])
  1753. else:
  1754. self.ui.splitter.setSizes([0, 1])
  1755. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1756. self.setup_obj_classes()
  1757. self.setup_recent_items()
  1758. self.setup_component_editor()
  1759. # #####################################################################################
  1760. # ######################### Auto-complete KEYWORDS ####################################
  1761. # #####################################################################################
  1762. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1763. 'aligndrill', 'aligndrillgrid', 'bbox', 'bounding_box', 'clear', 'cncjob', 'cutout',
  1764. 'delete', 'drillcncjob', 'export_gcode', 'export_svg', 'ext', 'exteriors', 'follow',
  1765. 'geo_union', 'geocutout', 'get_names', 'get_sys', 'getsys', 'help', 'import_svg',
  1766. 'interiors', 'isolate', 'join_excellon', 'join_excellons', 'join_geometries',
  1767. 'join_geometry', 'list_sys', 'listsys', 'milld', 'mills', 'milldrills', 'millslots',
  1768. 'mirror', 'ncc',
  1769. 'ncc_clear', 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  1770. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'paint',
  1771. 'pan', 'panel', 'panelize', 'plot_all', 'plot_objects', 'quit_flatcam',
  1772. 'save', 'save_project',
  1773. 'save_sys', 'scale',
  1774. 'set_active', 'set_sys', 'setsys', 'skew', 'subtract_poly', 'subtract_rectangle',
  1775. 'version', 'write_gcode'
  1776. ]
  1777. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'Marius', 'My Documents', 'Paste_1',
  1778. 'Repetier', 'Roland_MDX_20', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  1779. 'Toolchange_manual', 'Users', 'all', 'angle_x', 'angle_y', 'axis', 'axisoffset',
  1780. 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect', 'contour', 'default',
  1781. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dwell',
  1782. 'dwelltime', 'feedrate_z', 'grbl_11', 'grbl_laser', 'gridoffsety', 'gridx', 'gridy',
  1783. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  1784. 'milled_dias', 'minoffset', 'multidepth', 'name', 'offset', 'opt_type', 'order',
  1785. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  1786. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  1787. 'spacing_columns',
  1788. 'spacing_rows', 'spindlespeed', 'toolchange_xy', 'use_threads', 'value', 'x',
  1789. 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  1790. ]
  1791. self.tcl_keywords = [
  1792. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  1793. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  1794. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  1795. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  1796. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  1797. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  1798. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  1799. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  1800. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  1801. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  1802. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  1803. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  1804. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  1805. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  1806. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  1807. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  1808. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  1809. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  1810. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  1811. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  1812. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  1813. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  1814. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  1815. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  1816. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  1817. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  1818. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  1819. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  1820. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  1821. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  1822. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  1823. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  1824. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  1825. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  1826. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  1827. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  1828. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  1829. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  1830. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  1831. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  1832. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  1833. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  1834. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  1835. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  1836. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  1837. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  1838. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  1839. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  1840. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  1841. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  1842. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  1843. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  1844. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  1845. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  1846. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  1847. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  1848. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  1849. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  1850. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  1851. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  1852. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  1853. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  1854. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  1855. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  1856. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  1857. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  1858. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  1859. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  1860. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  1861. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  1862. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  1863. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  1864. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  1865. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  1866. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  1867. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  1868. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  1869. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1870. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1871. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1872. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1873. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1874. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1875. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1876. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1877. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1878. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1879. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1880. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1881. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1882. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1883. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1884. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1885. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1886. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1887. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1888. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1889. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1890. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1891. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1892. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1893. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1894. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1895. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1896. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1897. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1898. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1899. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1900. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1901. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1902. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1903. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1904. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1905. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1906. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1907. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1908. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1909. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1910. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1911. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1912. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1913. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1914. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1915. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1916. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1917. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1918. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1919. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1920. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1921. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1922. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1923. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1924. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1925. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1926. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1927. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1928. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1929. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1930. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1931. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1932. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1933. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1934. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1935. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1936. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1937. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1938. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1939. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1940. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1941. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1942. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1943. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1944. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1945. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1946. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1947. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1948. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1949. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1950. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1951. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1952. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1953. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1954. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1955. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1956. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1957. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1958. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1959. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1960. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1961. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1962. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1963. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1964. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1965. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1966. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1967. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1968. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1969. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1970. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1971. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1972. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1973. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1974. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1975. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1976. ]
  1977. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1978. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1979. # ####################################################################################
  1980. # ####################### Shell SETUP ################################################
  1981. # ####################################################################################
  1982. self.shell = FCShell(self, version=self.version)
  1983. self.shell._edit.set_model_data(self.myKeywords)
  1984. self.ui.code_editor.set_model_data(self.myKeywords)
  1985. self.shell.setWindowIcon(self.ui.app_icon)
  1986. self.shell.setWindowTitle("FlatCAM Shell")
  1987. self.shell.resize(*self.defaults["global_shell_shape"])
  1988. self.shell.append_output("FlatCAM %s - " % self.version)
  1989. self.shell.append_output(_("Open Source Software - Type help to get started\n\n"))
  1990. self.init_tcl()
  1991. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1992. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  1993. self.ui.shell_dock.setWidget(self.shell)
  1994. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1995. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1996. QtWidgets.QDockWidget.DockWidgetFloatable |
  1997. QtWidgets.QDockWidget.DockWidgetClosable)
  1998. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1999. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  2000. if self.defaults["global_shell_at_startup"]:
  2001. self.ui.shell_dock.show()
  2002. else:
  2003. self.ui.shell_dock.hide()
  2004. # ##################################################################################
  2005. # ###################### Tools and Plugins #########################################
  2006. # ##################################################################################
  2007. self.dblsidedtool = None
  2008. self.measurement_tool = None
  2009. self.panelize_tool = None
  2010. self.film_tool = None
  2011. self.paste_tool = None
  2012. self.calculator_tool = None
  2013. self.sub_tool = None
  2014. self.move_tool = None
  2015. self.cutout_tool = None
  2016. self.ncclear_tool = None
  2017. self.paint_tool = None
  2018. self.transform_tool = None
  2019. self.properties_tool = None
  2020. self.pdf_tool = None
  2021. self.image_tool = None
  2022. self.pcb_wizard_tool = None
  2023. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  2024. self.install_tools()
  2025. # ### System Font Parsing ###
  2026. # self.f_parse = ParseFont(self)
  2027. # self.parse_system_fonts()
  2028. # #####################################################################################
  2029. # ######################## Check for updates ##########################################
  2030. # #####################################################################################
  2031. # Separate thread (Not worker)
  2032. # Check for updates on startup but only if the user consent and the app is not in Beta version
  2033. if (self.beta is False or self.beta is None) and \
  2034. self.ui.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  2035. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  2036. self.thr2 = QtCore.QThread()
  2037. self.worker_task.emit({'fcn': self.version_check,
  2038. 'params': []})
  2039. self.thr2.start(QtCore.QThread.LowPriority)
  2040. # #####################################################################################
  2041. # ######################### Register files with FlatCAM; #############################
  2042. # ######################### It works only for Windows for now ########################
  2043. # #####################################################################################
  2044. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  2045. self.on_register_files()
  2046. # #####################################################################################
  2047. # ###################### Variables for global usage ###################################
  2048. # #####################################################################################
  2049. # coordinates for relative position display
  2050. self.rel_point1 = (0, 0)
  2051. self.rel_point2 = (0, 0)
  2052. # variable to store coordinates
  2053. self.pos = (0, 0)
  2054. self.pos_jump = (0, 0)
  2055. # variable to store mouse coordinates
  2056. self.mouse = [0, 0]
  2057. # decide if we have a double click or single click
  2058. self.doubleclick = False
  2059. # variable to store if a command is active (then the var is not None) and which one it is
  2060. self.command_active = None
  2061. # variable to store the status of moving selection action
  2062. # None value means that it's not an selection action
  2063. # True value = a selection from left to right
  2064. # False value = a selection from right to left
  2065. self.selection_type = None
  2066. # List to store the objects that are currently loaded in FlatCAM
  2067. # This list is updated on each object creation or object delete
  2068. self.all_objects_list = list()
  2069. # List to store the objects that are selected
  2070. self.sel_objects_list = list()
  2071. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  2072. self.key_modifiers = None
  2073. # Variable to hold the status of the axis
  2074. self.toggle_axis = True
  2075. # Variable to store the status of the fullscreen event
  2076. self.toggle_fscreen = False
  2077. # Variable to store the status of the code editor
  2078. self.toggle_codeeditor = False
  2079. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  2080. self.click_noproject = False
  2081. self.cursor = None
  2082. # Variable to store the GCODE that was edited
  2083. self.gcode_edited = ""
  2084. # reference for the self.ui.code_editor
  2085. self.reference_code_editor = None
  2086. self.script_code = ''
  2087. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  2088. self.preferences_changed_flag = False
  2089. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  2090. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  2091. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'pho',
  2092. 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top', 'tsm']
  2093. self.exc_list = ['drd', 'drl', 'exc', 'ncd', 'tap', 'txt', 'xln']
  2094. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  2095. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ncp', 'out', 'plt', 'ply', 'rol', 'sbp',
  2096. 'tap', 'xpi']
  2097. self.svg_list = ['svg']
  2098. self.dxf_list = ['dxf']
  2099. self.pdf_list = ['pdf']
  2100. self.prj_list = ['flatprj']
  2101. self.conf_list = ['flatconfig']
  2102. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  2103. # flag for polygons not cleared
  2104. self.poly_not_cleared = False
  2105. # VisPy visuals
  2106. self.isHovering = False
  2107. self.notHovering = True
  2108. # when True, the app has to return from any thread
  2109. self.abort_flag = False
  2110. # ###############################################################################
  2111. # ############# Save defaults to factory_defaults.FlatConfig file ###############
  2112. # ############# It's done only once after install ###############
  2113. # ###############################################################################
  2114. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  2115. fac_def_from_file = factory_file.read()
  2116. factory_defaults = json.loads(fac_def_from_file)
  2117. # if the file contain an empty dictionary then save the factory defaults into the file
  2118. if not factory_defaults:
  2119. self.save_factory_defaults(silent=False)
  2120. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  2121. initial_lay = 'compact'
  2122. self.on_layout(lay=initial_lay)
  2123. # Set the combobox in Preferences to the current layout
  2124. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  2125. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  2126. factory_file.close()
  2127. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  2128. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  2129. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  2130. # after the first run, this object should be False
  2131. self.defaults["first_run"] = False
  2132. # ###############################################################################
  2133. # ################# ADDING FlatCAM EDITORS section ##############################
  2134. # ###############################################################################
  2135. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  2136. # at the first launch of the App , the editors will not be functional.
  2137. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  2138. self.exc_editor = FlatCAMExcEditor(self)
  2139. self.grb_editor = FlatCAMGrbEditor(self)
  2140. self.log.debug("Finished adding FlatCAM Editor's.")
  2141. self.set_ui_title(name=_("New Project - Not saved"))
  2142. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  2143. current_platform = platform.architecture()[0]
  2144. if current_platform != '64bit':
  2145. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  2146. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  2147. # ###############################################################################
  2148. # ####################### Finished the CONSTRUCTOR ##############################
  2149. # ###############################################################################
  2150. App.log.debug("END of constructor. Releasing control.")
  2151. # #####################################################################################
  2152. # ########################## SHOW GUI #################################################
  2153. # #####################################################################################
  2154. # if the app is not started as headless, show it
  2155. if self.cmd_line_headless != 1:
  2156. # finish the splash
  2157. self.splash.finish(self.ui)
  2158. settings = QSettings("Open Source", "FlatCAM")
  2159. if settings.contains("maximized_gui"):
  2160. maximized_ui = settings.value('maximized_gui', type=bool)
  2161. if maximized_ui is True:
  2162. self.ui.showMaximized()
  2163. else:
  2164. self.ui.show()
  2165. else:
  2166. self.ui.show()
  2167. if self.defaults["global_systray_icon"]:
  2168. self.trayIcon.show()
  2169. else:
  2170. log.warning("******************* RUNNING HEADLESS *******************")
  2171. # #####################################################################################
  2172. # ########################## START-UP ARGUMENTS #######################################
  2173. # #####################################################################################
  2174. # test if the program was started with a script as parameter
  2175. if self.cmd_line_shellvar:
  2176. try:
  2177. cnt = 0
  2178. command_tcl = 0
  2179. for i in self.cmd_line_shellvar.split(','):
  2180. if i is not None:
  2181. try:
  2182. command_tcl = eval(i)
  2183. except:
  2184. command_tcl = i
  2185. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  2186. cnt += 1
  2187. # if there are Windows paths then replace the path separator with a Unix like one
  2188. if sys.platform == 'win32':
  2189. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  2190. self.shell._sysShell.exec_command(command_tcl_formatted, no_echo=True)
  2191. except Exception as ext:
  2192. print("ERROR: ", ext)
  2193. sys.exit(2)
  2194. if self.cmd_line_shellfile:
  2195. try:
  2196. if self.ui.shell_dock.isHidden():
  2197. self.ui.shell_dock.show()
  2198. with open(self.cmd_line_shellfile, "r") as myfile:
  2199. if show_splash:
  2200. self.splash.showMessage('%s: %ssec\n%s' % (
  2201. _("Canvas initialization started.\n"
  2202. "Canvas initialization finished in"), '%.2f' % self.used_time,
  2203. _("Executing Tcl Script ...")),
  2204. alignment=Qt.AlignBottom | Qt.AlignLeft,
  2205. color=QtGui.QColor("gray"))
  2206. cmd_line_shellfile_text = myfile.read()
  2207. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  2208. except Exception as ext:
  2209. print("ERROR: ", ext)
  2210. sys.exit(2)
  2211. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  2212. # the path/file_name must be enclosed in quotes if it contain spaces
  2213. if App.args:
  2214. self.args_at_startup.emit(App.args)
  2215. @staticmethod
  2216. def copy_and_overwrite(from_path, to_path):
  2217. """
  2218. From here:
  2219. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  2220. :param from_path: source path
  2221. :param to_path: destination path
  2222. :return: None
  2223. """
  2224. if os.path.exists(to_path):
  2225. shutil.rmtree(to_path)
  2226. try:
  2227. shutil.copytree(from_path, to_path)
  2228. except FileNotFoundError:
  2229. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  2230. shutil.copytree(from_new_path, to_path)
  2231. def on_startup_args(self, args, silent=False):
  2232. """
  2233. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  2234. :param args: a list containing the application args at startup
  2235. :return: None
  2236. """
  2237. if args is not None:
  2238. args_to_process = args
  2239. else:
  2240. args_to_process = App.args
  2241. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  2242. for argument in args_to_process:
  2243. if '.FlatPrj'.lower() in argument.lower():
  2244. try:
  2245. project_name = str(argument)
  2246. if project_name == "":
  2247. if silent is False:
  2248. self.inform.emit(_("Open cancelled."))
  2249. else:
  2250. # self.open_project(project_name)
  2251. run_from_arg = True
  2252. # self.worker_task.emit({'fcn': self.open_project,
  2253. # 'params': [project_name, run_from_arg]})
  2254. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  2255. except Exception as e:
  2256. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  2257. elif '.FlatConfig'.lower() in argument.lower():
  2258. try:
  2259. file_name = str(argument)
  2260. if file_name == "":
  2261. if silent is False:
  2262. self.inform.emit(_("Open Config file failed."))
  2263. else:
  2264. run_from_arg = True
  2265. # self.worker_task.emit({'fcn': self.open_config_file,
  2266. # 'params': [file_name, run_from_arg]})
  2267. self.open_config_file(file_name, run_from_arg=run_from_arg)
  2268. except Exception as e:
  2269. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  2270. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  2271. try:
  2272. file_name = str(argument)
  2273. if file_name == "":
  2274. if silent is False:
  2275. self.inform.emit(_("Open Script file failed."))
  2276. else:
  2277. if silent is False:
  2278. self.on_fileopenscript(name=file_name)
  2279. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  2280. self.on_filerunscript(name=file_name)
  2281. except Exception as e:
  2282. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  2283. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  2284. log.debug("App.on_startup_args() --> Quit event.")
  2285. sys.exit()
  2286. elif 'save'.lower() in argument.lower():
  2287. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  2288. self.save_defaults()
  2289. else:
  2290. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  2291. proc_arg = argument.lower()
  2292. for ext in exc_list:
  2293. proc_ext = ext.replace(' ', '')
  2294. proc_ext = '.%s' % proc_ext
  2295. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2296. file_name = str(argument)
  2297. if file_name == "":
  2298. if silent is False:
  2299. self.inform.emit(_("Open Excellon file failed."))
  2300. else:
  2301. self.on_fileopenexcellon(name=file_name)
  2302. return
  2303. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2304. for ext in gco_list:
  2305. proc_ext = ext.replace(' ', '')
  2306. proc_ext = '.%s' % proc_ext
  2307. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2308. print(proc_ext, proc_arg)
  2309. file_name = str(argument)
  2310. if file_name == "":
  2311. if silent is False:
  2312. self.inform.emit(_("Open GCode file failed."))
  2313. else:
  2314. self.on_fileopengcode(name=file_name)
  2315. return
  2316. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2317. for ext in grb_list:
  2318. proc_ext = ext.replace(' ', '')
  2319. proc_ext = '.%s' % proc_ext
  2320. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2321. file_name = str(argument)
  2322. if file_name == "":
  2323. if silent is False:
  2324. self.inform.emit(_("Open Gerber file failed."))
  2325. else:
  2326. self.on_fileopengerber(name=file_name)
  2327. return
  2328. # if it reached here without already returning then the app was registered with a file that it does not
  2329. # recognize therefore we must quit
  2330. sys.exit(2)
  2331. def set_ui_title(self, name):
  2332. """
  2333. Sets the title of the main window.
  2334. :param name: String that store the project path and project name
  2335. :return: None
  2336. """
  2337. self.ui.setWindowTitle('FlatCAM %s %s - %s %s' %
  2338. (self.version,
  2339. ('BETA' if self.beta else ''),
  2340. platform.architecture()[0],
  2341. name)
  2342. )
  2343. def defaults_read_form(self):
  2344. """
  2345. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2346. :return: None
  2347. """
  2348. for option in self.defaults_form_fields:
  2349. try:
  2350. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2351. except Exception as e:
  2352. log.debug("App.defaults_read_form() --> %s" % str(e))
  2353. def defaults_write_form(self, factor=None, fl_units=None):
  2354. """
  2355. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2356. self.defaults dictionary.
  2357. :param factor: will apply a factor to the values that written in the GUI elements
  2358. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2359. :return: None
  2360. """
  2361. for option in self.defaults:
  2362. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2363. # try:
  2364. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2365. # except KeyError:
  2366. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2367. # # TODO: Rethink this?
  2368. # pass
  2369. def defaults_write_form_field(self, field, factor=None, units=None):
  2370. """
  2371. Basically it is the worker in the self.defaults_write_form()
  2372. :param field: the GUI element in Preferences GUI to be updated
  2373. :param factor: factor to be applied to the field parameter
  2374. :param units: current FLatCAM measuring units
  2375. :return: None, it updates GUI elements
  2376. """
  2377. try:
  2378. if factor is None:
  2379. if units is None:
  2380. self.defaults_form_fields[field].set_value(self.defaults[field])
  2381. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2382. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=6)
  2383. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2384. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=4)
  2385. else:
  2386. if units is None:
  2387. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  2388. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2389. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=6)
  2390. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2391. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=4)
  2392. except KeyError:
  2393. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  2394. # TODO: Rethink this?
  2395. pass
  2396. except AttributeError:
  2397. log.debug(field)
  2398. def clear_pool(self):
  2399. """
  2400. Clear the multiprocessing pool and calls garbage collector.
  2401. :return: None
  2402. """
  2403. self.pool.close()
  2404. self.pool = Pool()
  2405. self.pool_recreated.emit(self.pool)
  2406. gc.collect()
  2407. def install_tools(self):
  2408. """
  2409. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2410. Instantiation of the Tools classes.
  2411. The order that the tools are installed is important as they can depend on each other install position.
  2412. :return: None
  2413. """
  2414. self.dblsidedtool = DblSidedTool(self)
  2415. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  2416. self.measurement_tool = Measurement(self)
  2417. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  2418. self.panelize_tool = Panelize(self)
  2419. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  2420. self.film_tool = Film(self)
  2421. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  2422. self.paste_tool = SolderPaste(self)
  2423. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  2424. self.calculator_tool = ToolCalculator(self)
  2425. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'), separator=True)
  2426. self.sub_tool = ToolSub(self)
  2427. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menutool, separator=True)
  2428. self.move_tool = ToolMove(self)
  2429. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  2430. before=self.ui.menueditorigin)
  2431. self.cutout_tool = CutOut(self)
  2432. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  2433. before=self.measurement_tool.menuAction)
  2434. self.ncclear_tool = NonCopperClear(self)
  2435. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  2436. before=self.measurement_tool.menuAction, separator=True)
  2437. self.paint_tool = ToolPaint(self)
  2438. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  2439. before=self.measurement_tool.menuAction, separator=True)
  2440. self.transform_tool = ToolTransform(self)
  2441. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  2442. self.properties_tool = Properties(self)
  2443. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  2444. self.pdf_tool = ToolPDF(self)
  2445. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  2446. separator=True)
  2447. self.image_tool = ToolImage(self)
  2448. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  2449. separator=True)
  2450. self.pcb_wizard_tool = PcbWizard(self)
  2451. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  2452. self.log.debug("Tools are installed.")
  2453. def remove_tools(self):
  2454. """
  2455. Will remove all the actions in the Tool menu.
  2456. :return: None
  2457. """
  2458. for act in self.ui.menutool.actions():
  2459. self.ui.menutool.removeAction(act)
  2460. def init_tools(self):
  2461. """
  2462. Initialize the Tool tab in the notebook side of the central widget.
  2463. Remove the actions in the Tools menu.
  2464. Instantiate again the FlatCAM tools (plugins).
  2465. All this is required when changing the layout: standard, compact etc.
  2466. :return: None
  2467. """
  2468. log.debug("init_tools()")
  2469. # delete the data currently in the Tools Tab and the Tab itself
  2470. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2471. if widget is not None:
  2472. widget.deleteLater()
  2473. self.ui.notebook.removeTab(2)
  2474. # rebuild the Tools Tab
  2475. self.ui.tool_tab = QtWidgets.QWidget()
  2476. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2477. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2478. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2479. self.ui.tool_scroll_area = VerticalScrollArea()
  2480. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2481. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2482. # first remove all of them
  2483. self.remove_tools()
  2484. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2485. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  2486. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2487. # third install all of them
  2488. self.install_tools()
  2489. self.log.debug("Tools are initialized.")
  2490. # def parse_system_fonts(self):
  2491. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2492. # 'params': []})
  2493. def connect_toolbar_signals(self):
  2494. """
  2495. Reconnect the signals to the actions in the toolbar.
  2496. This has to be done each time after the FlatCAM tools are removed/installed.
  2497. :return: None
  2498. """
  2499. # Toolbar
  2500. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2501. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2502. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2503. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2504. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2505. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2506. self.ui.replot_btn.triggered.connect(self.plot_all)
  2507. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2508. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2509. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2510. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2511. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2512. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2513. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2514. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2515. self.ui.delete_btn.triggered.connect(self.on_delete)
  2516. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2517. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  2518. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  2519. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  2520. # Tools Toolbar Signals
  2521. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2522. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2523. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2524. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2525. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2526. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2527. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2528. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2529. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2530. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2531. def object2editor(self):
  2532. """
  2533. Send the current Geometry or Excellon object (if any) into the it's editor.
  2534. :return: None
  2535. """
  2536. self.report_usage("object2editor()")
  2537. edited_object = self.collection.get_active()
  2538. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2539. isinstance(edited_object, FlatCAMExcellon):
  2540. pass
  2541. else:
  2542. self.inform.emit('[WARNING_NOTCL] %s' %
  2543. _("Select a Geometry, Gerber or Excellon Object to edit."))
  2544. return
  2545. if isinstance(edited_object, FlatCAMGeometry):
  2546. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2547. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2548. # we set the notebook to hidden
  2549. self.ui.splitter.setSizes([0, 1])
  2550. if edited_object.multigeo is True:
  2551. edited_tools = [int(x.text()) for x in edited_object.ui.geo_tools_table.selectedItems()]
  2552. if len(edited_tools) > 1:
  2553. self.inform.emit('[WARNING_NOTCL] %s' %
  2554. _("Simultanoeus editing of tools geometry in a MultiGeo Geometry "
  2555. "is not possible.\n"
  2556. "Edit only one geometry at a time."))
  2557. # determine the tool dia of the selected tool
  2558. selected_tooldia = float(edited_object.ui.geo_tools_table.item((edited_tools[0] - 1), 1).text())
  2559. # now find the key in the edited_object.tools that has this tooldia
  2560. multi_tool = 1
  2561. for tool in edited_object.tools:
  2562. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2563. multi_tool = tool
  2564. break
  2565. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2566. else:
  2567. self.geo_editor.edit_fcgeometry(edited_object)
  2568. # set call source to the Editor we go into
  2569. self.call_source = 'geo_editor'
  2570. elif isinstance(edited_object, FlatCAMExcellon):
  2571. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2572. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2573. if self.ui.splitter.sizes()[0] == 0:
  2574. self.ui.splitter.setSizes([1, 1])
  2575. self.exc_editor.edit_fcexcellon(edited_object)
  2576. # set call source to the Editor we go into
  2577. self.call_source = 'exc_editor'
  2578. elif isinstance(edited_object, FlatCAMGerber):
  2579. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2580. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2581. if self.ui.splitter.sizes()[0] == 0:
  2582. self.ui.splitter.setSizes([1, 1])
  2583. self.grb_editor.edit_fcgerber(edited_object)
  2584. # set call source to the Editor we go into
  2585. self.call_source = 'grb_editor'
  2586. # make sure that we can't select another object while in Editor Mode:
  2587. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2588. self.ui.project_frame.setDisabled(True)
  2589. # delete any selection shape that might be active as they are not relevant in Editor
  2590. self.delete_selection_shape()
  2591. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2592. self.ui.plot_tab_area.protectTab(0)
  2593. self.inform.emit('[WARNING_NOTCL] %s' %
  2594. _("Editor is activated ..."))
  2595. self.should_we_save = True
  2596. def editor2object(self, cleanup=None):
  2597. """
  2598. Transfers the Geometry or Excellon from it's editor to the current object.
  2599. :return: None
  2600. """
  2601. self.report_usage("editor2object()")
  2602. # do not update a geometry or excellon object unless it comes out of an editor
  2603. if self.call_source != 'app':
  2604. edited_obj = self.collection.get_active()
  2605. if cleanup is None:
  2606. msgbox = QtWidgets.QMessageBox()
  2607. msgbox.setText(_("Do you want to save the edited object?"))
  2608. msgbox.setWindowTitle(_("Close Editor"))
  2609. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2610. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2611. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2612. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2613. msgbox.setDefaultButton(bt_yes)
  2614. msgbox.exec_()
  2615. response = msgbox.clickedButton()
  2616. if response == bt_yes:
  2617. # clean the Tools Tab
  2618. self.ui.tool_scroll_area.takeWidget()
  2619. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2620. self.ui.notebook.setTabText(2, "Tool")
  2621. if isinstance(edited_obj, FlatCAMGeometry):
  2622. obj_type = "Geometry"
  2623. if cleanup is None:
  2624. self.geo_editor.update_fcgeometry(edited_obj)
  2625. self.geo_editor.update_options(edited_obj)
  2626. self.geo_editor.deactivate()
  2627. # update the geo object options so it is including the bounding box values
  2628. try:
  2629. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2630. edited_obj.options['xmin'] = xmin
  2631. edited_obj.options['ymin'] = ymin
  2632. edited_obj.options['xmax'] = xmax
  2633. edited_obj.options['ymax'] = ymax
  2634. except AttributeError as e:
  2635. self.inform.emit('[WARNING] %s' %
  2636. _("Object empty after edit."))
  2637. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2638. elif isinstance(edited_obj, FlatCAMGerber):
  2639. obj_type = "Gerber"
  2640. if cleanup is None:
  2641. self.grb_editor.update_fcgerber()
  2642. self.grb_editor.update_options(edited_obj)
  2643. self.grb_editor.deactivate_grb_editor()
  2644. # delete the old object (the source object) if it was an empty one
  2645. if len(edited_obj.solid_geometry) == 0:
  2646. old_name = edited_obj.options['name']
  2647. self.collection.set_active(old_name)
  2648. self.collection.delete_active()
  2649. elif isinstance(edited_obj, FlatCAMExcellon):
  2650. obj_type = "Excellon"
  2651. if cleanup is None:
  2652. self.exc_editor.update_fcexcellon(edited_obj)
  2653. self.exc_editor.update_options(edited_obj)
  2654. self.exc_editor.deactivate()
  2655. else:
  2656. self.inform.emit('[WARNING_NOTCL] %s' %
  2657. _("Select a Gerber, Geometry or Excellon Object to update."))
  2658. return
  2659. self.inform.emit('[selected] %s %s' %
  2660. (obj_type, _("is updated, returning to App...")))
  2661. elif response == bt_no:
  2662. # clean the Tools Tab
  2663. self.ui.tool_scroll_area.takeWidget()
  2664. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2665. self.ui.notebook.setTabText(2, "Tool")
  2666. if isinstance(edited_obj, FlatCAMGeometry):
  2667. self.geo_editor.deactivate()
  2668. elif isinstance(edited_obj, FlatCAMGerber):
  2669. self.grb_editor.deactivate_grb_editor()
  2670. elif isinstance(edited_obj, FlatCAMExcellon):
  2671. self.exc_editor.deactivate()
  2672. # set focus on the project tab
  2673. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  2674. else:
  2675. self.inform.emit('[WARNING_NOTCL] %s' %
  2676. _("Select a Gerber, Geometry or Excellon Object to update."))
  2677. return
  2678. elif response == bt_cancel:
  2679. return
  2680. else:
  2681. if isinstance(edited_obj, FlatCAMGeometry):
  2682. self.geo_editor.deactivate()
  2683. elif isinstance(edited_obj, FlatCAMGerber):
  2684. self.grb_editor.deactivate_grb_editor()
  2685. elif isinstance(edited_obj, FlatCAMExcellon):
  2686. self.exc_editor.deactivate()
  2687. else:
  2688. self.inform.emit('[WARNING_NOTCL] %s' %
  2689. _("Select a Gerber, Geometry or Excellon Object to update."))
  2690. return
  2691. # if notebook is hidden we show it
  2692. if self.ui.splitter.sizes()[0] == 0:
  2693. self.ui.splitter.setSizes([1, 1])
  2694. # restore the call_source to app
  2695. self.call_source = 'app'
  2696. edited_obj.plot()
  2697. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2698. self.ui.plot_tab_area.protectTab(0)
  2699. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2700. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2701. self.ui.project_frame.setDisabled(False)
  2702. def get_last_folder(self):
  2703. """
  2704. Get the folder path from where the last file was opened.
  2705. :return: String, last opened folder path
  2706. """
  2707. return self.defaults["global_last_folder"]
  2708. def get_last_save_folder(self):
  2709. """
  2710. Get the folder path from where the last file was saved.
  2711. :return: String, last saved folder path
  2712. """
  2713. loc = self.defaults["global_last_save_folder"]
  2714. if loc is None:
  2715. loc = self.defaults["global_last_folder"]
  2716. if loc is None:
  2717. loc = os.path.dirname(__file__)
  2718. return loc
  2719. def report_usage(self, resource):
  2720. """
  2721. Increments usage counter for the given resource
  2722. in self.defaults['global_stats'].
  2723. :param resource: Name of the resource.
  2724. :return: None
  2725. """
  2726. if resource in self.defaults['global_stats']:
  2727. self.defaults['global_stats'][resource] += 1
  2728. else:
  2729. self.defaults['global_stats'][resource] = 1
  2730. def init_tcl(self):
  2731. """
  2732. Initialize the TCL Shell. A dock widget that holds the GUI interface to the FlatCAM command line.
  2733. :return: None
  2734. """
  2735. if hasattr(self, 'tcl'):
  2736. # self.tcl = None
  2737. # TODO we need to clean non default variables and procedures here
  2738. # new object cannot be used here as it will not remember values created for next passes,
  2739. # because tcl was execudted in old instance of TCL
  2740. pass
  2741. else:
  2742. self.tcl = tk.Tcl()
  2743. self.setup_shell()
  2744. self.log.debug("TCL Shell has been initialized.")
  2745. # TODO: This shouldn't be here.
  2746. class TclErrorException(Exception):
  2747. """
  2748. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  2749. """
  2750. pass
  2751. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2752. """
  2753. Shows a message on the FlatCAM Shell
  2754. :param msg: Message to display.
  2755. :param show: Opens the shell.
  2756. :param error: Shows the message as an error.
  2757. :param warning: Shows the message as an warning.
  2758. :param success: Shows the message as an success.
  2759. :param selected: Indicate that something was selected on canvas
  2760. :return: None
  2761. """
  2762. if show:
  2763. self.ui.shell_dock.show()
  2764. try:
  2765. if error:
  2766. self.shell.append_error(msg + "\n")
  2767. elif warning:
  2768. self.shell.append_warning(msg + "\n")
  2769. elif success:
  2770. self.shell.append_success(msg + "\n")
  2771. elif selected:
  2772. self.shell.append_selected(msg + "\n")
  2773. else:
  2774. self.shell.append_output(msg + "\n")
  2775. except AttributeError:
  2776. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2777. def raise_tcl_unknown_error(self, unknownException):
  2778. """
  2779. Raise exception if is different type than TclErrorException
  2780. this is here mainly to show unknown errors inside TCL shell console.
  2781. :param unknownException:
  2782. :return:
  2783. """
  2784. if not isinstance(unknownException, self.TclErrorException):
  2785. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2786. else:
  2787. raise unknownException
  2788. def display_tcl_error(self, error, error_info=None):
  2789. """
  2790. Escape bracket [ with '\' otherwise there is error
  2791. "ERROR: missing close-bracket" instead of real error
  2792. :param error: it may be text or exception
  2793. :param error_info: Some informations about the error
  2794. :return: None
  2795. """
  2796. if isinstance(error, Exception):
  2797. exc_type, exc_value, exc_traceback = error_info
  2798. if not isinstance(error, self.TclErrorException):
  2799. show_trace = 1
  2800. else:
  2801. show_trace = int(self.defaults['global_verbose_error_level'])
  2802. if show_trace > 0:
  2803. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2804. trc_formated = []
  2805. for a in reversed(trc):
  2806. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2807. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  2808. else:
  2809. text = "%s" % error
  2810. else:
  2811. text = error
  2812. text = text.replace('[', '\\[').replace('"', '\\"')
  2813. self.tcl.eval('return -code error "%s"' % text)
  2814. def raise_tcl_error(self, text):
  2815. """
  2816. This method pass exception from python into TCL as error, so we get stacktrace and reason
  2817. :param text: text of error
  2818. :return: raise exception
  2819. """
  2820. self.display_tcl_error(text)
  2821. raise self.TclErrorException(text)
  2822. def exec_command(self, text, no_echo=False):
  2823. """
  2824. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2825. Also handles execution in separated threads
  2826. :param text: FlatCAM TclCommand with parameters
  2827. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  2828. will create crashes of the _Expandable_Edit widget
  2829. :return: output if there was any
  2830. """
  2831. self.report_usage('exec_command')
  2832. result = self.exec_command_test(text, False, no_echo=no_echo)
  2833. # MS: added this method call so the geometry is updated once the TCL command is executed
  2834. # if no_plot is None:
  2835. # self.plot_all()
  2836. return result
  2837. def exec_command_test(self, text, reraise=True, no_echo=False):
  2838. """
  2839. Same as exec_command(...) with additional control over exceptions.
  2840. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2841. :param text: Input command
  2842. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  2843. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  2844. will create crashes of the _Expandable_Edit widget
  2845. :return: Output from the command
  2846. """
  2847. tcl_command_string = str(text)
  2848. try:
  2849. if no_echo is False:
  2850. self.shell.open_proccessing() # Disables input box.
  2851. result = self.tcl.eval(str(tcl_command_string))
  2852. if result != 'None' and no_echo is False:
  2853. self.shell.append_output(result + '\n')
  2854. except tk.TclError as e:
  2855. # This will display more precise answer if something in TCL shell fails
  2856. result = self.tcl.eval("set errorInfo")
  2857. self.log.error("Exec command Exception: %s" % (result + '\n'))
  2858. if no_echo is False:
  2859. self.shell.append_error('ERROR: ' + result + '\n')
  2860. # Show error in console and just return or in test raise exception
  2861. if reraise:
  2862. raise e
  2863. finally:
  2864. if no_echo is False:
  2865. self.shell.close_proccessing()
  2866. pass
  2867. return result
  2868. # """
  2869. # Code below is unsused. Saved for later.
  2870. # """
  2871. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  2872. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  2873. # self.log.debug(parts)
  2874. # try:
  2875. # if parts[0] not in commands:
  2876. # self.shell.append_error("Unknown command\n")
  2877. # return
  2878. #
  2879. # #import inspect
  2880. # #inspect.getargspec(someMethod)
  2881. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  2882. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  2883. # self.shell.append_error(
  2884. # "Command %s takes %d arguments. %d given.\n" %
  2885. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  2886. # )
  2887. # return
  2888. #
  2889. # cmdfcn = commands[parts[0]]["fcn"]
  2890. # cmdconv = commands[parts[0]]["converters"]
  2891. # if len(parts) - 1 > 0:
  2892. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  2893. # else:
  2894. # retval = cmdfcn()
  2895. # retfcn = commands[parts[0]]["retfcn"]
  2896. # if retval and retfcn(retval):
  2897. # self.shell.append_output(retfcn(retval) + "\n")
  2898. #
  2899. # except Exception as e:
  2900. # #self.shell.append_error(''.join(traceback.format_exc()))
  2901. # #self.shell.append_error("?\n")
  2902. # self.shell.append_error(str(e) + "\n")
  2903. def info(self, msg):
  2904. """
  2905. Informs the user. Normally on the status bar, optionally
  2906. also on the shell.
  2907. :param msg: Text to write.
  2908. :return: None
  2909. """
  2910. # Type of message in brackets at the beginning of the message.
  2911. match = re.search("\[([^\]]+)\](.*)", msg)
  2912. if match:
  2913. level = match.group(1)
  2914. msg_ = match.group(2)
  2915. self.ui.fcinfo.set_status(str(msg_), level=level)
  2916. if level.lower() == "error":
  2917. self.shell_message(msg, error=True, show=True)
  2918. elif level.lower() == "warning":
  2919. self.shell_message(msg, warning=True, show=True)
  2920. elif level.lower() == "error_notcl":
  2921. self.shell_message(msg, error=True, show=False)
  2922. elif level.lower() == "warning_notcl":
  2923. self.shell_message(msg, warning=True, show=False)
  2924. elif level.lower() == "success":
  2925. self.shell_message(msg, success=True, show=False)
  2926. elif level.lower() == "selected":
  2927. self.shell_message(msg, selected=True, show=False)
  2928. else:
  2929. self.shell_message(msg, show=False)
  2930. else:
  2931. self.ui.fcinfo.set_status(str(msg), level="info")
  2932. # make sure that if the message is to clear the infobar with a space
  2933. # is not printed over and over on the shell
  2934. if msg != '':
  2935. self.shell_message(msg)
  2936. def restore_toolbar_view(self):
  2937. """
  2938. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  2939. was saved in the defaults dictionary.
  2940. :return: None
  2941. """
  2942. tb = self.defaults["global_toolbar_view"]
  2943. if tb & 1:
  2944. self.ui.toolbarfile.setVisible(True)
  2945. else:
  2946. self.ui.toolbarfile.setVisible(False)
  2947. if tb & 2:
  2948. self.ui.toolbargeo.setVisible(True)
  2949. else:
  2950. self.ui.toolbargeo.setVisible(False)
  2951. if tb & 4:
  2952. self.ui.toolbarview.setVisible(True)
  2953. else:
  2954. self.ui.toolbarview.setVisible(False)
  2955. if tb & 8:
  2956. self.ui.toolbartools.setVisible(True)
  2957. else:
  2958. self.ui.toolbartools.setVisible(False)
  2959. if tb & 16:
  2960. self.ui.exc_edit_toolbar.setVisible(True)
  2961. else:
  2962. self.ui.exc_edit_toolbar.setVisible(False)
  2963. if tb & 32:
  2964. self.ui.geo_edit_toolbar.setVisible(True)
  2965. else:
  2966. self.ui.geo_edit_toolbar.setVisible(False)
  2967. if tb & 64:
  2968. self.ui.grb_edit_toolbar.setVisible(True)
  2969. else:
  2970. self.ui.grb_edit_toolbar.setVisible(False)
  2971. if tb & 128:
  2972. self.ui.snap_toolbar.setVisible(True)
  2973. else:
  2974. self.ui.snap_toolbar.setVisible(False)
  2975. if tb & 256:
  2976. self.ui.toolbarshell.setVisible(True)
  2977. else:
  2978. self.ui.toolbarshell.setVisible(False)
  2979. def load_defaults(self, filename):
  2980. """
  2981. Loads the aplication's default settings from current_defaults.FlatConfig into
  2982. ``self.defaults``.
  2983. :return: None
  2984. """
  2985. try:
  2986. f = open(self.data_path + "/" + filename + ".FlatConfig")
  2987. options = f.read()
  2988. f.close()
  2989. except IOError:
  2990. self.log.error("Could not load defaults file.")
  2991. self.inform.emit('[ERROR] %s' %
  2992. _("Could not load defaults file."))
  2993. # in case the defaults file can't be loaded, show all toolbars
  2994. self.defaults["global_toolbar_view"] = 511
  2995. return
  2996. try:
  2997. defaults = json.loads(options)
  2998. except:
  2999. # in case the defaults file can't be loaded, show all toolbars
  3000. self.defaults["global_toolbar_view"] = 511
  3001. e = sys.exc_info()[0]
  3002. App.log.error(str(e))
  3003. self.inform.emit('[ERROR] %s' %
  3004. _("Failed to parse defaults file."))
  3005. return
  3006. self.defaults.update(defaults)
  3007. log.debug("FlatCAM defaults loaded from: %s" % filename)
  3008. # restore the toolbar view
  3009. self.restore_toolbar_view()
  3010. def on_import_preferences(self):
  3011. """
  3012. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  3013. ``self.defaults``.
  3014. :return: None
  3015. """
  3016. self.report_usage("on_import_preferences")
  3017. App.log.debug("on_import_preferences()")
  3018. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  3019. try:
  3020. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3021. directory=self.data_path,
  3022. filter=filter_)
  3023. except TypeError:
  3024. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3025. filter=filter_)
  3026. filename = str(filename)
  3027. if filename == "":
  3028. self.inform.emit('[WARNING_NOTCL] %s' %
  3029. _("FlatCAM preferences import cancelled."))
  3030. else:
  3031. try:
  3032. f = open(filename)
  3033. options = f.read()
  3034. f.close()
  3035. except IOError:
  3036. self.log.error("Could not load defaults file.")
  3037. self.inform.emit('[ERROR_NOTCL] %s' %
  3038. _("Could not load defaults file."))
  3039. return
  3040. try:
  3041. defaults_from_file = json.loads(options)
  3042. except Exception as e:
  3043. e = sys.exc_info()[0]
  3044. App.log.error(str(e))
  3045. self.inform.emit('[ERROR_NOTCL] %s' %
  3046. _("Failed to parse defaults file."))
  3047. return
  3048. self.defaults.update(defaults_from_file)
  3049. self.on_preferences_edited()
  3050. self.inform.emit('[success] %s: %s' %
  3051. (_("Imported Defaults from"), filename))
  3052. def on_export_preferences(self):
  3053. """
  3054. Save the defaults dictionary to a file.
  3055. :return: None
  3056. """
  3057. self.report_usage("on_export_preferences")
  3058. App.log.debug("on_export_preferences()")
  3059. defaults_file_content = None
  3060. self.date = str(datetime.today()).rpartition('.')[0]
  3061. self.date = ''.join(c for c in self.date if c not in ':-')
  3062. self.date = self.date.replace(' ', '_')
  3063. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  3064. try:
  3065. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  3066. caption=_("Export FlatCAM Preferences"),
  3067. directory=self.data_path + '/preferences_' + self.date,
  3068. filter=filter__
  3069. )
  3070. except TypeError:
  3071. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  3072. filter=filter__)
  3073. filename = str(filename)
  3074. defaults_from_file = {}
  3075. if filename == "":
  3076. self.inform.emit('[WARNING_NOTCL] %s' %
  3077. _("FlatCAM preferences export cancelled."))
  3078. return
  3079. else:
  3080. try:
  3081. f = open(filename, 'w')
  3082. defaults_file_content = f.read()
  3083. f.close()
  3084. except PermissionError:
  3085. self.inform.emit('[WARNING] %s' %
  3086. _("Permission denied, saving not possible.\n"
  3087. "Most likely another app is holding the file open and not accessible."))
  3088. return
  3089. except IOError:
  3090. App.log.debug('Creating a new preferences file ...')
  3091. f = open(filename, 'w')
  3092. json.dump({}, f)
  3093. f.close()
  3094. except:
  3095. e = sys.exc_info()[0]
  3096. App.log.error("Could not load defaults file.")
  3097. App.log.error(str(e))
  3098. self.inform.emit('[ERROR_NOTCL] %s' %
  3099. _("Could not load preferences file."))
  3100. return
  3101. try:
  3102. defaults_from_file = json.loads(defaults_file_content)
  3103. except:
  3104. App.log.warning("Trying to read an empty Preferences file. Continue.")
  3105. # Update options
  3106. self.defaults_read_form()
  3107. defaults_from_file.update(self.defaults)
  3108. self.propagate_defaults(silent=True)
  3109. # Save update options
  3110. try:
  3111. f = open(filename, "w")
  3112. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  3113. f.close()
  3114. except:
  3115. self.inform.emit('[ERROR_NOTCL] %s' %
  3116. _("Failed to write defaults to file."))
  3117. return
  3118. if self.defaults["global_open_style"] is False:
  3119. self.file_opened.emit("preferences", filename)
  3120. self.file_saved.emit("preferences", filename)
  3121. self.inform.emit('[success] %s: %s' %
  3122. (_("Exported preferences to"), filename))
  3123. def on_preferences_open_folder(self):
  3124. """
  3125. Will open an Explorer window set to the folder path where the FlatCAM preferences files are usually saved.
  3126. :return: None
  3127. """
  3128. self.report_usage("on_preferences_open_folder()")
  3129. if sys.platform == 'win32':
  3130. subprocess.Popen('explorer %s' % self.data_path)
  3131. elif sys.platform == 'darwin':
  3132. os.system('open "%s"' % self.data_path)
  3133. else:
  3134. subprocess.Popen(['xdg-open', self.data_path])
  3135. self.inform.emit('[success] %s' %
  3136. _("FlatCAM Preferences Folder opened."))
  3137. def save_geometry(self, x, y, width, height, notebook_width):
  3138. """
  3139. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  3140. launch of the application.
  3141. :param x: X position of the main window
  3142. :param y: Y position of the main window
  3143. :param width: width of the main window
  3144. :param height: height of the main window
  3145. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  3146. :return: None
  3147. """
  3148. self.defaults["global_def_win_x"] = x
  3149. self.defaults["global_def_win_y"] = y
  3150. self.defaults["global_def_win_w"] = width
  3151. self.defaults["global_def_win_h"] = height
  3152. self.defaults["global_def_notebook_width"] = notebook_width
  3153. self.save_defaults()
  3154. def message_dialog(self, title, message, kind="info"):
  3155. """
  3156. Builds and show a custom QMessageBox to be used in FlatCAM.
  3157. :param title: title of the QMessageBox
  3158. :param message: message to be displayed
  3159. :param kind: type of QMessageBox; will display a specific icon.
  3160. :return:
  3161. """
  3162. icon = {"info": QtWidgets.QMessageBox.Information,
  3163. "warning": QtWidgets.QMessageBox.Warning,
  3164. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  3165. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  3166. dlg.setText(message)
  3167. dlg.exec_()
  3168. def register_recent(self, kind, filename):
  3169. """
  3170. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  3171. dictionary.
  3172. :param kind: type of file that was opened
  3173. :param filename: the path and file name for the file that was opened
  3174. :return:
  3175. """
  3176. self.log.debug("register_recent()")
  3177. self.log.debug(" %s" % kind)
  3178. self.log.debug(" %s" % filename)
  3179. record = {'kind': str(kind), 'filename': str(filename)}
  3180. if record in self.recent:
  3181. return
  3182. if record in self.recent_projects:
  3183. return
  3184. if record['kind'] == 'project':
  3185. self.recent_projects.insert(0, record)
  3186. else:
  3187. self.recent.insert(0, record)
  3188. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  3189. self.recent.pop()
  3190. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  3191. self.recent_projects.pop()
  3192. try:
  3193. f = open(self.data_path + '/recent.json', 'w')
  3194. except IOError:
  3195. App.log.error("Failed to open recent items file for writing.")
  3196. self.inform.emit('[ERROR_NOTCL] %s' %
  3197. _('Failed to open recent files file for writing.'))
  3198. return
  3199. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  3200. f.close()
  3201. try:
  3202. fp = open(self.data_path + '/recent_projects.json', 'w')
  3203. except IOError:
  3204. App.log.error("Failed to open recent items file for writing.")
  3205. self.inform.emit('[ERROR_NOTCL] %s' %
  3206. _('Failed to open recent projects file for writing.'))
  3207. return
  3208. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  3209. fp.close()
  3210. # Re-build the recent items menu
  3211. self.setup_recent_items()
  3212. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  3213. """
  3214. Creates a new specialized FlatCAMObj and attaches it to the application,
  3215. this is, updates the GUI accordingly, any other records and plots it.
  3216. This method is thread-safe.
  3217. Notes:
  3218. * If the name is in use, the self.collection will modify it
  3219. when appending it to the collection. There is no need to handle
  3220. name conflicts here.
  3221. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  3222. :type kind: str
  3223. :param name: Name for the object.
  3224. :type name: str
  3225. :param initialize: Function to run after creation of the object but before it is attached to the application.
  3226. The function is called with 2 parameters: the new object and the App instance.
  3227. :type initialize: function
  3228. :param active:
  3229. :param fit:
  3230. :param plot: If to plot the resulting object
  3231. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  3232. self.colleaction
  3233. :return: None
  3234. :rtype: None
  3235. """
  3236. App.log.debug("new_object()")
  3237. obj_plot = plot
  3238. obj_autoselected = autoselected
  3239. t0 = time.time() # Debug
  3240. # ## Create object
  3241. classdict = {
  3242. "gerber": FlatCAMGerber,
  3243. "excellon": FlatCAMExcellon,
  3244. "cncjob": FlatCAMCNCjob,
  3245. "geometry": FlatCAMGeometry
  3246. }
  3247. App.log.debug("Calling object constructor...")
  3248. obj = classdict[kind](name)
  3249. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  3250. # Set options from "Project options" form
  3251. self.options_read_form()
  3252. # IMPORTANT
  3253. # The key names in defaults and options dictionary's are not random:
  3254. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  3255. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  3256. # the options from project options form into the self.options. After that, below, depending on the type of
  3257. # object that is created, it will strip the name of the object and the underline (if the original key was
  3258. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  3259. # "toolchange"
  3260. for option in self.options:
  3261. if option.find(kind + "_") == 0:
  3262. oname = option[len(kind) + 1:]
  3263. obj.options[oname] = self.options[option]
  3264. obj.isHovering = False
  3265. obj.notHovering = True
  3266. # Initialize as per user request
  3267. # User must take care to implement initialize
  3268. # in a thread-safe way as is is likely that we
  3269. # have been invoked in a separate thread.
  3270. t1 = time.time()
  3271. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  3272. try:
  3273. return_value = initialize(obj, self)
  3274. except Exception as e:
  3275. msg = '[ERROR_NOTCL] %s' % \
  3276. _("An internal error has ocurred. See shell.\n")
  3277. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  3278. msg += traceback.format_exc()
  3279. self.inform.emit(msg)
  3280. # if str(e) == "Empty Geometry":
  3281. # self.inform.emit("[ERROR_NOTCL] )
  3282. # else:
  3283. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  3284. return "fail"
  3285. t2 = time.time()
  3286. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  3287. if return_value == 'fail':
  3288. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  3289. return "fail"
  3290. # Check units and convert if necessary
  3291. # This condition CAN be true because initialize() can change obj.units
  3292. if self.options["units"].upper() != obj.units.upper():
  3293. self.inform.emit('%s: %s' %
  3294. (_("Converting units to "), self.options["units"]))
  3295. obj.convert_units(self.options["units"])
  3296. t3 = time.time()
  3297. self.log.debug("%f seconds converting units." % (t3 - t2))
  3298. # Create the bounding box for the object and then add the results to the obj.options
  3299. try:
  3300. xmin, ymin, xmax, ymax = obj.bounds()
  3301. obj.options['xmin'] = xmin
  3302. obj.options['ymin'] = ymin
  3303. obj.options['xmax'] = xmax
  3304. obj.options['ymax'] = ymax
  3305. except Exception as e:
  3306. log.warning("The object has no bounds properties. %s" % str(e))
  3307. return "fail"
  3308. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  3309. # Move the object to the main thread and let the app know that it is available.
  3310. obj.moveToThread(self.main_thread)
  3311. self.object_created.emit(obj, obj_plot, obj_autoselected)
  3312. return obj
  3313. def new_excellon_object(self):
  3314. """
  3315. Creates a new, blank Excellon object.
  3316. :return: None
  3317. """
  3318. self.report_usage("new_excellon_object()")
  3319. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  3320. def new_geometry_object(self):
  3321. """
  3322. Creates a new, blank and single-tool Geometry object.
  3323. :return: None
  3324. """
  3325. self.report_usage("new_geometry_object()")
  3326. def initialize(obj, self):
  3327. obj.multitool = False
  3328. self.new_object('geometry', 'new_geo', initialize, plot=False)
  3329. def new_gerber_object(self):
  3330. """
  3331. Creates a new, blank Gerber object.
  3332. :return: None
  3333. """
  3334. self.report_usage("new_gerber_object()")
  3335. def initialize(grb_obj, self):
  3336. grb_obj.multitool = False
  3337. grb_obj.source_file = []
  3338. grb_obj.multigeo = False
  3339. grb_obj.follow = False
  3340. grb_obj.apertures = {}
  3341. grb_obj.solid_geometry = []
  3342. try:
  3343. grb_obj.options['xmin'] = 0
  3344. grb_obj.options['ymin'] = 0
  3345. grb_obj.options['xmax'] = 0
  3346. grb_obj.options['ymax'] = 0
  3347. except KeyError:
  3348. pass
  3349. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3350. def on_object_created(self, obj, plot, autoselect):
  3351. """
  3352. Event callback for object creation.
  3353. It will add the new object to the collection. After that it will plot the object in a threaded way
  3354. :param obj: The newly created FlatCAM object.
  3355. :param plot: if the newly create object t obe plotted
  3356. :param autoselect: if the newly created object to be autoselected after creation
  3357. :return: None
  3358. """
  3359. t0 = time.time() # DEBUG
  3360. self.log.debug("on_object_created()")
  3361. # The Collection might change the name if there is a collision
  3362. self.collection.append(obj)
  3363. # after adding the object to the collection always update the list of objects that are in the collection
  3364. self.all_objects_list = self.collection.get_list()
  3365. # self.inform.emit('[selected] %s created & selected: %s' %
  3366. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3367. if obj.kind == 'gerber':
  3368. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3369. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  3370. elif obj.kind == 'excellon':
  3371. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3372. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  3373. elif obj.kind == 'cncjob':
  3374. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3375. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  3376. elif obj.kind == 'geometry':
  3377. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3378. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  3379. # update the SHELL auto-completer model with the name of the new object
  3380. self.myKeywords.append(obj.options['name'])
  3381. self.shell._edit.set_model_data(self.myKeywords)
  3382. self.ui.code_editor.set_model_data(self.myKeywords)
  3383. if autoselect:
  3384. # select the just opened object but deselect the previous ones
  3385. self.collection.set_all_inactive()
  3386. self.collection.set_active(obj.options["name"])
  3387. else:
  3388. self.collection.set_all_inactive()
  3389. # here it is done the object plotting
  3390. def worker_task(t_obj):
  3391. with self.proc_container.new(_("Plotting")):
  3392. if isinstance(t_obj, FlatCAMCNCjob):
  3393. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3394. else:
  3395. t_obj.plot()
  3396. t1 = time.time() # DEBUG
  3397. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3398. self.object_plotted.emit(t_obj)
  3399. # Send to worker
  3400. # self.worker.add_task(worker_task, [self])
  3401. if plot is True:
  3402. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3403. def on_object_changed(self, obj):
  3404. """
  3405. Called whenever the geometry of the object was changed in some way.
  3406. This require the update of it's bounding values so it can be the selected on canvas.
  3407. Update the bounding box data from obj.options
  3408. :param obj: the object that was changed
  3409. :return: None
  3410. """
  3411. xmin, ymin, xmax, ymax = obj.bounds()
  3412. obj.options['xmin'] = xmin
  3413. obj.options['ymin'] = ymin
  3414. obj.options['xmax'] = xmax
  3415. obj.options['ymax'] = ymax
  3416. log.debug("Object changed, updating the bounding box data on self.options")
  3417. # delete the old selection shape
  3418. self.delete_selection_shape()
  3419. self.should_we_save = True
  3420. def on_object_plotted(self, obj):
  3421. """
  3422. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3423. :param obj: object to be fit into view
  3424. :return: None
  3425. """
  3426. self.on_zoom_fit(None)
  3427. def options_read_form(self):
  3428. """
  3429. Same as it's equivalent from the defaults.
  3430. self.options use to store the preferences per project. No longer used.
  3431. :return: None
  3432. """
  3433. for option in self.options_form_fields:
  3434. self.options[option] = self.options_form_fields[option].get_value()
  3435. def options_write_form(self):
  3436. """
  3437. Same as it's equivalent from the defaults.
  3438. self.options use to store the preferences per project. No longer used.
  3439. :return: None
  3440. """
  3441. for option in self.options:
  3442. self.options_write_form_field(option)
  3443. def options_write_form_field(self, field):
  3444. """
  3445. Same as it's equivalent from the defaults.
  3446. self.options use to store the preferences per project. No longer used.
  3447. :return: None
  3448. """
  3449. try:
  3450. self.options_form_fields[field].set_value(self.options[field])
  3451. except KeyError:
  3452. # Changed from error to debug. This allows to have data stored
  3453. # which is not user-editable.
  3454. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  3455. pass
  3456. def on_about(self):
  3457. """
  3458. Displays the "about" dialog found in the Menu --> Help.
  3459. :return: None
  3460. """
  3461. self.report_usage("on_about")
  3462. version = self.version
  3463. version_date = self.version_date
  3464. beta = self.beta
  3465. class AboutDialog(QtWidgets.QDialog):
  3466. def __init__(self, parent=None):
  3467. QtWidgets.QDialog.__init__(self, parent)
  3468. # Icon and title
  3469. self.setWindowIcon(parent.app_icon)
  3470. self.setWindowTitle(_("About FlatCAM"))
  3471. self.resize(600, 200)
  3472. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3473. # self.setStyleSheet(
  3474. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3475. # "background-attachment: fixed"
  3476. # )
  3477. # bgimage = QtGui.QImage('share/flatcam_icon256.png')
  3478. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3479. # palette = QtGui.QPalette()
  3480. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3481. # self.setPalette(palette)
  3482. logo = QtWidgets.QLabel()
  3483. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  3484. title = QtWidgets.QLabel(
  3485. "<font size=8><B>FlatCAM</B></font><BR>"
  3486. "{title}<BR>"
  3487. "<BR>"
  3488. "<BR>"
  3489. # "<B>{devel}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3490. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  3491. # "<b>{down}</B> area &nbsp;&nbsp;&nbsp;&nbsp;"
  3492. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  3493. # "<b> {issue}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3494. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  3495. "<B>{issue}</B></a><BR>".format(
  3496. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  3497. devel=_("Development"),
  3498. down=_("DOWNLOAD"),
  3499. issue=_("Issue tracker"))
  3500. )
  3501. title.setOpenExternalLinks(True)
  3502. closebtn = QtWidgets.QPushButton(_("Close"))
  3503. tab_widget = QtWidgets.QTabWidget()
  3504. description_label = QtWidgets.QLabel(
  3505. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  3506. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  3507. version=version,
  3508. beta=('BETA' if beta else ''),
  3509. date=version_date,
  3510. arch=platform.architecture()[0])
  3511. )
  3512. description_label.setOpenExternalLinks(True)
  3513. license_label = QtWidgets.QLabel(
  3514. _(
  3515. '(c) Copyright 2014 Juan Pablo Caram.\n\n'
  3516. 'Licensed under the MIT license:\n'
  3517. 'http://www.opensource.org/licenses/mit-license.php\n\n'
  3518. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  3519. 'of this software and associated documentation files (the "Software"), to deal\n'
  3520. 'in the Software without restriction, including without limitation the rights\n'
  3521. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  3522. 'copies of the Software, and to permit persons to whom the Software is\n'
  3523. ' furnished to do so, subject to the following conditions:\n\n'
  3524. 'The above copyright notice and this permission notice shall be included in\n'
  3525. 'all copies or substantial portions of the Software.\n\n'
  3526. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  3527. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  3528. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  3529. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  3530. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  3531. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  3532. 'THE SOFTWARE.'
  3533. )
  3534. )
  3535. license_label.setOpenExternalLinks(True)
  3536. # layouts
  3537. layout1 = QtWidgets.QVBoxLayout()
  3538. layout1_1 = QtWidgets.QHBoxLayout()
  3539. layout1_2 = QtWidgets.QHBoxLayout()
  3540. layout2 = QtWidgets.QHBoxLayout()
  3541. layout3 = QtWidgets.QHBoxLayout()
  3542. self.setLayout(layout1)
  3543. layout1.addLayout(layout1_1)
  3544. layout1.addLayout(layout1_2)
  3545. layout1.addLayout(layout2)
  3546. layout1.addLayout(layout3)
  3547. layout1_1.addStretch()
  3548. layout1_1.addWidget(description_label)
  3549. layout1_2.addWidget(tab_widget)
  3550. self.splash_tab = QtWidgets.QWidget()
  3551. self.splash_tab.setObjectName("splash_about")
  3552. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  3553. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  3554. tab_widget.addTab(self.splash_tab, _("Splash"))
  3555. self.programmmers_tab = QtWidgets.QWidget()
  3556. self.programmmers_tab.setObjectName("programmers_about")
  3557. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  3558. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  3559. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  3560. self.translators_tab = QtWidgets.QWidget()
  3561. self.translators_tab.setObjectName("translators_about")
  3562. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  3563. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  3564. tab_widget.addTab(self.translators_tab, _("Translators"))
  3565. self.license_tab = QtWidgets.QWidget()
  3566. self.license_tab.setObjectName("license_about")
  3567. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  3568. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  3569. tab_widget.addTab(self.license_tab, _("License"))
  3570. self.splash_tab_layout.addWidget(logo, stretch=0)
  3571. self.splash_tab_layout.addWidget(title, stretch=1)
  3572. pal = QtGui.QPalette()
  3573. pal.setColor(QtGui.QPalette.Background, Qt.white)
  3574. self.prog_form_lay = QtWidgets.QFormLayout()
  3575. self.prog_form_lay.setHorizontalSpacing(20)
  3576. prog_widget = QtWidgets.QWidget()
  3577. prog_widget.setLayout(self.prog_form_lay)
  3578. prog_scroll = QtWidgets.QScrollArea()
  3579. prog_scroll.setWidget(prog_widget)
  3580. prog_scroll.setWidgetResizable(True)
  3581. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3582. prog_scroll.setPalette(pal)
  3583. self.programmmers_tab_layout.addWidget(prog_scroll)
  3584. self.prog_form_lay.addRow(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")),
  3585. QtWidgets.QLabel('<b>%s</b>' % _("Status")))
  3586. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Juan Pablo Caram"),
  3587. QtWidgets.QLabel('%s' % _("Program Author")))
  3588. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Denis Hayrullin"))
  3589. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Kamil Sopko"))
  3590. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Marius Stanciu"),
  3591. QtWidgets.QLabel('%s' % _("Maintainer >=2019")))
  3592. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3593. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Alexandru Lazar"))
  3594. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Matthieu Berthomé"))
  3595. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Mike Evans"))
  3596. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Victor Benso"))
  3597. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3598. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Barnaby Walters"))
  3599. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"))
  3600. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Lei Zheng"))
  3601. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Marco A Quezada"))
  3602. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3603. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Cedric Dussud"))
  3604. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Chris Hemingway"))
  3605. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Damian Wrobel"))
  3606. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Daniel Sallin"))
  3607. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3608. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Bruno Vunderl"))
  3609. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Gonzalo Lopez"))
  3610. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Jakob Staudt"))
  3611. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Mike Smith"))
  3612. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3613. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Lubos Medovarsky"))
  3614. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Steve Martina"))
  3615. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Thomas Duffin"))
  3616. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3617. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@Idechix"))
  3618. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@SM"))
  3619. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@grbf"))
  3620. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@Symonty"))
  3621. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@mgix"))
  3622. self.translator_grid_lay = QtWidgets.QGridLayout()
  3623. # trans_widget = QtWidgets.QWidget()
  3624. # trans_widget.setLayout(self.translator_grid_lay)
  3625. # self.translators_tab_layout.addWidget(trans_widget)
  3626. # self.translators_tab_layout.addStretch()
  3627. trans_widget = QtWidgets.QWidget()
  3628. trans_widget.setLayout(self.translator_grid_lay)
  3629. trans_scroll = QtWidgets.QScrollArea()
  3630. trans_scroll.setWidget(trans_widget)
  3631. trans_scroll.setWidgetResizable(True)
  3632. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3633. trans_scroll.setPalette(pal)
  3634. self.translators_tab_layout.addWidget(trans_scroll)
  3635. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  3636. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  3637. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  3638. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Brasilian - Portuguese"), 1, 0)
  3639. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  3640. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 1, 2)
  3641. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 2, 0)
  3642. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 2, 1)
  3643. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 2)
  3644. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 3, 0)
  3645. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 3, 1)
  3646. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  3647. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 4, 0)
  3648. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 4, 1)
  3649. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 4, 2)
  3650. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 5, 0)
  3651. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 5, 1)
  3652. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 2)
  3653. self.translator_grid_lay.setColumnStretch(0, 0)
  3654. self.translators_tab_layout.addStretch()
  3655. self.license_tab_layout.addWidget(license_label)
  3656. self.license_tab_layout.addStretch()
  3657. layout3.addStretch()
  3658. layout3.addWidget(closebtn)
  3659. closebtn.clicked.connect(self.accept)
  3660. AboutDialog(self.ui).exec_()
  3661. def on_file_savedefaults(self):
  3662. """
  3663. Callback for menu item File->Save Defaults. Saves application default options
  3664. ``self.defaults`` to current_defaults.FlatConfig.
  3665. :return: None
  3666. """
  3667. self.save_defaults()
  3668. # def on_app_exit(self):
  3669. # self.report_usage("on_app_exit()")
  3670. #
  3671. # if self.collection.get_list():
  3672. # msgbox = QtWidgets.QMessageBox()
  3673. # # msgbox.setText("<B>Save changes ...</B>")
  3674. # msgbox.setText("There are files/objects opened in FlatCAM. "
  3675. # "\n"
  3676. # "Do you want to Save the project?")
  3677. # msgbox.setWindowTitle("Save changes")
  3678. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3679. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  3680. # QtWidgets.QMessageBox.Cancel)
  3681. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  3682. #
  3683. # response = msgbox.exec_()
  3684. #
  3685. # if response == QtWidgets.QMessageBox.Yes:
  3686. # self.on_file_saveprojectas(thread=False)
  3687. # elif response == QtWidgets.QMessageBox.Cancel:
  3688. # return
  3689. # self.save_defaults()
  3690. # else:
  3691. # self.save_defaults()
  3692. # log.debug("Application defaults saved ... Exit event.")
  3693. # QtWidgets.qApp.quit()
  3694. def save_defaults(self, silent=False, data_path=None, first_time=False):
  3695. """
  3696. Saves application default options
  3697. ``self.defaults`` to current_defaults.FlatConfig file.
  3698. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  3699. used at the next launch of the application.
  3700. :param silent: whether to display a message in status bar or not; boolean
  3701. :param data_path: the path where to save the preferences file (current_defaults.FlatConfig)
  3702. When the application is portable it should be a mobile location.
  3703. :return: None
  3704. """
  3705. self.report_usage("save_defaults")
  3706. if data_path is None:
  3707. data_path = self.data_path
  3708. # Read options from file
  3709. try:
  3710. f = open(data_path + "/current_defaults.FlatConfig")
  3711. defaults_file_content = f.read()
  3712. f.close()
  3713. except:
  3714. e = sys.exc_info()[0]
  3715. App.log.error("Could not load defaults file.")
  3716. App.log.error(str(e))
  3717. self.inform.emit('[ERROR_NOTCL] %s' %
  3718. _("Could not load defaults file."))
  3719. return
  3720. try:
  3721. defaults = json.loads(defaults_file_content)
  3722. except:
  3723. e = sys.exc_info()[0]
  3724. App.log.error("Failed to parse defaults file.")
  3725. App.log.error(str(e))
  3726. self.inform.emit('[ERROR_NOTCL] %s' %
  3727. _("Failed to parse defaults file."))
  3728. return
  3729. # Update options
  3730. self.defaults_read_form()
  3731. defaults.update(self.defaults)
  3732. self.propagate_defaults(silent=True)
  3733. # Save the toolbar view
  3734. tb_status = 0
  3735. if self.ui.toolbarfile.isVisible():
  3736. tb_status += 1
  3737. if self.ui.toolbargeo.isVisible():
  3738. tb_status += 2
  3739. if self.ui.toolbarview.isVisible():
  3740. tb_status += 4
  3741. if self.ui.toolbartools.isVisible():
  3742. tb_status += 8
  3743. if self.ui.exc_edit_toolbar.isVisible():
  3744. tb_status += 16
  3745. if self.ui.geo_edit_toolbar.isVisible():
  3746. tb_status += 32
  3747. if self.ui.grb_edit_toolbar.isVisible():
  3748. tb_status += 64
  3749. if self.ui.snap_toolbar.isVisible():
  3750. tb_status += 128
  3751. if self.ui.toolbarshell.isVisible():
  3752. tb_status += 256
  3753. if first_time is False:
  3754. self.defaults["global_toolbar_view"] = tb_status
  3755. # Save update options
  3756. try:
  3757. f = open(data_path + "/current_defaults.FlatConfig", "w")
  3758. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  3759. f.close()
  3760. except:
  3761. self.inform.emit('[ERROR_NOTCL] %s' %
  3762. _("Failed to write defaults to file."))
  3763. return
  3764. if not silent:
  3765. self.inform.emit('[success] %s' %
  3766. _("Preferences saved."))
  3767. def save_factory_defaults(self, silent=False, data_path=None):
  3768. """
  3769. Saves application factory default options
  3770. ``self.defaults`` to factory_defaults.FlatConfig.
  3771. It's a one time job done just after the first install.
  3772. :param silent: whether to display a message in status bar or not; boolean
  3773. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  3774. When the application is portable it should be a mobile location.
  3775. :return: None
  3776. """
  3777. self.report_usage("save_factory_defaults")
  3778. if data_path is None:
  3779. data_path = self.data_path
  3780. # Read options from file
  3781. try:
  3782. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  3783. factory_defaults_file_content = f_f_def.read()
  3784. f_f_def.close()
  3785. except:
  3786. e = sys.exc_info()[0]
  3787. App.log.error("Could not load factory defaults file.")
  3788. App.log.error(str(e))
  3789. self.inform.emit('[ERROR_NOTCL] %s' %
  3790. _("Could not load factory defaults file."))
  3791. return
  3792. try:
  3793. factory_defaults = json.loads(factory_defaults_file_content)
  3794. except:
  3795. e = sys.exc_info()[0]
  3796. App.log.error("Failed to parse factory defaults file.")
  3797. App.log.error(str(e))
  3798. self.inform.emit('[ERROR_NOTCL] %s' %
  3799. _("Failed to parse factory defaults file."))
  3800. return
  3801. # Update options
  3802. self.defaults_read_form()
  3803. factory_defaults.update(self.defaults)
  3804. self.propagate_defaults(silent=True)
  3805. # Save update options
  3806. try:
  3807. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  3808. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  3809. f_f_def_s.close()
  3810. except:
  3811. self.inform.emit('[ERROR_NOTCL] %s' %
  3812. _("Failed to write factory defaults to file."))
  3813. return
  3814. if silent is False:
  3815. self.inform.emit(_("Factory defaults saved."))
  3816. def final_save(self):
  3817. """
  3818. Callback for doing a preferences save to file whenever the application is about to quit.
  3819. If the project has changes, it will ask the user to save the project.
  3820. :return: None
  3821. """
  3822. if self.save_in_progress:
  3823. self.inform.emit('[WARNING_NOTCL] %s' %
  3824. _("Application is saving the project. Please wait ..."))
  3825. return
  3826. if self.should_we_save and self.collection.get_list():
  3827. msgbox = QtWidgets.QMessageBox()
  3828. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  3829. "\n"
  3830. "Do you want to Save the project?"))
  3831. msgbox.setWindowTitle(_("Save changes"))
  3832. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3833. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  3834. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  3835. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3836. msgbox.setDefaultButton(bt_yes)
  3837. msgbox.exec_()
  3838. response = msgbox.clickedButton()
  3839. if response == bt_yes:
  3840. try:
  3841. self.trayIcon.hide()
  3842. except:
  3843. pass
  3844. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  3845. elif response == bt_no:
  3846. try:
  3847. self.trayIcon.hide()
  3848. except:
  3849. pass
  3850. self.quit_application()
  3851. elif response == bt_cancel:
  3852. return
  3853. else:
  3854. try:
  3855. self.trayIcon.hide()
  3856. except:
  3857. pass
  3858. self.quit_application()
  3859. def quit_application(self):
  3860. """
  3861. Called (as a pyslot or not) when the application is quit.
  3862. :return: None
  3863. """
  3864. self.save_defaults()
  3865. log.debug("App.final_save() --> App Defaults saved.")
  3866. if self.cmd_line_headless != 1:
  3867. # save app state to file
  3868. settings = QSettings("Open Source", "FlatCAM")
  3869. settings.setValue('saved_gui_state', self.ui.saveState())
  3870. settings.setValue('maximized_gui', self.ui.isMaximized())
  3871. settings.setValue('language', self.ui.general_defaults_form.general_app_group.language_cb.get_value())
  3872. settings.setValue(
  3873. 'notebook_font_size',
  3874. self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  3875. )
  3876. settings.setValue('axis_font_size',
  3877. self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value())
  3878. settings.setValue(
  3879. 'textbox_font_size',
  3880. self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  3881. )
  3882. settings.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  3883. # This will write the setting to the platform specific storage.
  3884. del settings
  3885. log.debug("App.final_save() --> App UI state saved.")
  3886. QtWidgets.qApp.quit()
  3887. def on_portable_checked(self, state):
  3888. """
  3889. Callback called when the checkbox in Preferences GUI is checked.
  3890. It will set the application as portable by creating the preferences and recent files in the
  3891. 'config' folder found in the FlatCAM installation folder.
  3892. :param state: boolean, the state of the checkbox when clicked/checked
  3893. :return:
  3894. """
  3895. line_no = 0
  3896. data = None
  3897. if sys.platform != 'win32':
  3898. # this won't work in Linux or MacOS
  3899. return
  3900. # test if the app was frozen and choose the path for the configuration file
  3901. if getattr(sys, "frozen", False) is True:
  3902. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  3903. else:
  3904. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  3905. config_file = current_data_path + '\\configuration.txt'
  3906. try:
  3907. with open(config_file, 'r') as f:
  3908. try:
  3909. data = f.readlines()
  3910. except Exception as e:
  3911. log.debug('App.__init__() -->%s' % str(e))
  3912. return
  3913. except FileNotFoundError:
  3914. pass
  3915. for line in data:
  3916. line = line.strip('\n')
  3917. param = str(line).rpartition('=')
  3918. if param[0] == 'portable':
  3919. break
  3920. line_no += 1
  3921. if state:
  3922. data[line_no] = 'portable=True\n'
  3923. # create the new defauults files
  3924. # create current_defaults.FlatConfig file if there is none
  3925. try:
  3926. f = open(current_data_path + '/current_defaults.FlatConfig')
  3927. f.close()
  3928. except IOError:
  3929. App.log.debug('Creating empty current_defaults.FlatConfig')
  3930. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3931. json.dump({}, f)
  3932. f.close()
  3933. # create factory_defaults.FlatConfig file if there is none
  3934. try:
  3935. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3936. f.close()
  3937. except IOError:
  3938. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3939. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3940. json.dump({}, f)
  3941. f.close()
  3942. try:
  3943. f = open(current_data_path + '/recent.json')
  3944. f.close()
  3945. except IOError:
  3946. App.log.debug('Creating empty recent.json')
  3947. f = open(current_data_path + '/recent.json', 'w')
  3948. json.dump([], f)
  3949. f.close()
  3950. try:
  3951. fp = open(current_data_path + '/recent_projects.json')
  3952. fp.close()
  3953. except IOError:
  3954. App.log.debug('Creating empty recent_projects.json')
  3955. fp = open(current_data_path + '/recent_projects.json', 'w')
  3956. json.dump([], fp)
  3957. fp.close()
  3958. # save the current defaults to the new defaults file
  3959. self.save_defaults(silent=True, data_path=current_data_path)
  3960. self.save_factory_defaults(silent=True, data_path=current_data_path)
  3961. else:
  3962. data[line_no] = 'portable=False\n'
  3963. with open(config_file, 'w') as f:
  3964. f.writelines(data)
  3965. def on_toggle_shell(self):
  3966. """
  3967. Toggle shell: if is visible close it, if it is closed then open it
  3968. :return:
  3969. """
  3970. self.report_usage("on_toggle_shell()")
  3971. if self.ui.shell_dock.isVisible():
  3972. self.ui.shell_dock.hide()
  3973. else:
  3974. self.ui.shell_dock.show()
  3975. def on_register_files(self, obj_type=None):
  3976. """
  3977. Called whenever there is a need to register file extensions with FlatCAM.
  3978. Works only in Windows and should be called only when FlatCAM is run in Windows.
  3979. :param obj_type: the type of object to be register for.
  3980. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  3981. :return: None
  3982. """
  3983. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  3984. new_reg_path = 'Software\\Classes\\'
  3985. # find if the current user is admin
  3986. try:
  3987. is_admin = os.getuid() == 0
  3988. except AttributeError:
  3989. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  3990. if is_admin is True:
  3991. root_path = winreg.HKEY_LOCAL_MACHINE
  3992. else:
  3993. root_path = winreg.HKEY_CURRENT_USER
  3994. # create the keys
  3995. def set_reg(name, root_path, new_reg_path, value):
  3996. try:
  3997. winreg.CreateKey(root_path, new_reg_path)
  3998. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  3999. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  4000. return True
  4001. except WindowsError:
  4002. return False
  4003. # delete key in registry
  4004. def delete_reg(root_path, reg_path, key_to_del):
  4005. key_to_del_path = reg_path + key_to_del
  4006. try:
  4007. winreg.DeleteKey(root_path, key_to_del_path)
  4008. return True
  4009. except WindowsError:
  4010. return False
  4011. if obj_type is None or obj_type == 'excellon':
  4012. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4013. exc_list = [x for x in exc_list if x != '']
  4014. # register all keys in the Preferences window
  4015. for ext in exc_list:
  4016. new_k = new_reg_path + '.%s' % ext
  4017. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4018. # and unregister those that are no longer in the Preferences windows but are in the file
  4019. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  4020. if ext not in exc_list:
  4021. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4022. # now write the updated extensions to the self.defaults
  4023. # new_ext = ''
  4024. # for ext in exc_list:
  4025. # new_ext = new_ext + ext + ', '
  4026. # self.defaults["fa_excellon"] = new_ext
  4027. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  4028. if obj_type is None or obj_type == 'gcode':
  4029. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4030. gco_list = [x for x in gco_list if x != '']
  4031. # register all keys in the Preferences window
  4032. for ext in gco_list:
  4033. new_k = new_reg_path + '.%s' % ext
  4034. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4035. # and unregister those that are no longer in the Preferences windows but are in the file
  4036. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  4037. if ext not in gco_list:
  4038. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4039. # now write the updated extensions to the self.defaults
  4040. # new_ext = ''
  4041. # for ext in gco_list:
  4042. # new_ext = new_ext + ext + ', '
  4043. # self.defaults["fa_gcode"] = new_ext
  4044. self.inform.emit('[success] %s' %
  4045. _("Selected GCode file extensions registered with FlatCAM."))
  4046. if obj_type is None or obj_type == 'gerber':
  4047. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4048. grb_list = [x for x in grb_list if x != '']
  4049. # register all keys in the Preferences window
  4050. for ext in grb_list:
  4051. new_k = new_reg_path + '.%s' % ext
  4052. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4053. # and unregister those that are no longer in the Preferences windows but are in the file
  4054. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  4055. if ext not in grb_list:
  4056. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4057. # now write the updated extensions to the self.defaults
  4058. # new_ext = ''
  4059. # for ext in grb_list:
  4060. # new_ext = new_ext + ext + ', '
  4061. # self.defaults["fa_gerber"] = new_ext
  4062. self.inform.emit('[success] %s' %
  4063. _("Selected Gerber file extensions registered with FlatCAM."))
  4064. def add_extension(self, ext_type):
  4065. if ext_type == 'excellon':
  4066. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4067. if new_ext == '':
  4068. return
  4069. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4070. if new_ext in old_val:
  4071. return
  4072. old_val.append(new_ext)
  4073. old_val.sort()
  4074. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4075. if ext_type == 'gcode':
  4076. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4077. if new_ext == '':
  4078. return
  4079. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4080. if new_ext in old_val:
  4081. return
  4082. old_val.append(new_ext)
  4083. old_val.sort()
  4084. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4085. if ext_type == 'gerber':
  4086. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4087. if new_ext == '':
  4088. return
  4089. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4090. if new_ext in old_val:
  4091. return
  4092. old_val.append(new_ext)
  4093. old_val.sort()
  4094. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4095. if ext_type == 'keyword':
  4096. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4097. if new_kw == '':
  4098. return
  4099. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4100. if new_kw in old_val:
  4101. return
  4102. old_val.append(new_kw)
  4103. old_val.sort()
  4104. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4105. # update the self.myKeywords so the model is updated
  4106. self.autocomplete_kw_list = \
  4107. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4108. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4109. self.shell._edit.set_model_data(self.myKeywords)
  4110. self.ui.code_editor.set_model_data(self.myKeywords)
  4111. def del_extension(self, ext_type):
  4112. if ext_type == 'excellon':
  4113. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4114. if new_ext == '':
  4115. return
  4116. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4117. if new_ext not in old_val:
  4118. return
  4119. old_val.remove(new_ext)
  4120. old_val.sort()
  4121. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4122. if ext_type == 'gcode':
  4123. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4124. if new_ext == '':
  4125. return
  4126. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4127. if new_ext not in old_val:
  4128. return
  4129. old_val.remove(new_ext)
  4130. old_val.sort()
  4131. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4132. if ext_type == 'gerber':
  4133. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4134. if new_ext == '':
  4135. return
  4136. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4137. if new_ext not in old_val:
  4138. return
  4139. old_val.remove(new_ext)
  4140. old_val.sort()
  4141. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4142. if ext_type == 'keyword':
  4143. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4144. if new_kw == '':
  4145. return
  4146. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4147. if new_kw not in old_val:
  4148. return
  4149. old_val.remove(new_kw)
  4150. old_val.sort()
  4151. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4152. # update the self.myKeywords so the model is updated
  4153. self.autocomplete_kw_list = \
  4154. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4155. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4156. self.shell._edit.set_model_data(self.myKeywords)
  4157. self.ui.code_editor.set_model_data(self.myKeywords)
  4158. def restore_extensions(self, ext_type):
  4159. if ext_type == 'excellon':
  4160. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  4161. # for the ability to open Excellon files with .txt extension
  4162. new_exc_list = deepcopy(self.exc_list)
  4163. try:
  4164. new_exc_list.remove('txt')
  4165. except ValueError:
  4166. pass
  4167. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  4168. if ext_type == 'gcode':
  4169. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  4170. if ext_type == 'gerber':
  4171. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  4172. if ext_type == 'keyword':
  4173. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  4174. # update the self.myKeywords so the model is updated
  4175. self.autocomplete_kw_list = self.default_keywords
  4176. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4177. self.shell._edit.set_model_data(self.myKeywords)
  4178. self.ui.code_editor.set_model_data(self.myKeywords)
  4179. def delete_all_extensions(self, ext_type):
  4180. if ext_type == 'excellon':
  4181. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  4182. if ext_type == 'gcode':
  4183. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  4184. if ext_type == 'gerber':
  4185. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  4186. if ext_type == 'keyword':
  4187. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  4188. # update the self.myKeywords so the model is updated
  4189. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  4190. self.shell._edit.set_model_data(self.myKeywords)
  4191. self.ui.code_editor.set_model_data(self.myKeywords)
  4192. def on_edit_join(self, name=None):
  4193. """
  4194. Callback for Edit->Join. Joins the selected geometry objects into
  4195. a new one.
  4196. :return: None
  4197. """
  4198. self.report_usage("on_edit_join()")
  4199. obj_name_single = str(name) if name else "Combo_SingleGeo"
  4200. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  4201. tooldias = []
  4202. geo_type_list = set()
  4203. objs = self.collection.get_selected()
  4204. if len(objs) < 2:
  4205. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4206. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4207. return 'fail'
  4208. for obj in objs:
  4209. geo_type_list.add(obj.multigeo)
  4210. # if len(geo_type_list) == 1 means that all list elements are the same
  4211. if len(geo_type_list) != 1:
  4212. self.inform.emit('[ERROR] %s' %
  4213. _("Failed join. The Geometry objects are of different types.\n"
  4214. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  4215. "convert from one to another and retry joining \n"
  4216. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  4217. "the result may not be what was expected. \n"
  4218. "Check the generated GCODE."))
  4219. return
  4220. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  4221. if True in geo_type_list:
  4222. def initialize(obj, app):
  4223. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=True)
  4224. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4225. for v in obj.tools.values():
  4226. v['data']['name'] = obj_name_multi
  4227. self.new_object("geometry", obj_name_multi, initialize)
  4228. else:
  4229. def initialize(obj, app):
  4230. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=False)
  4231. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4232. for v in obj.tools.values():
  4233. v['data']['name'] = obj_name_single
  4234. self.new_object("geometry", obj_name_single, initialize)
  4235. self.should_we_save = True
  4236. def on_edit_join_exc(self):
  4237. """
  4238. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  4239. a new Excellon.
  4240. :return: None
  4241. """
  4242. self.report_usage("on_edit_join_exc()")
  4243. objs = self.collection.get_selected()
  4244. for obj in objs:
  4245. if not isinstance(obj, FlatCAMExcellon):
  4246. self.inform.emit('[ERROR_NOTCL] %s' %
  4247. _("Failed. Excellon joining works only on Excellon objects."))
  4248. return
  4249. if len(objs) < 2:
  4250. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4251. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4252. return 'fail'
  4253. def initialize(obj, app):
  4254. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=obj)
  4255. self.new_object("excellon", 'Combo_Excellon', initialize)
  4256. self.should_we_save = True
  4257. def on_edit_join_grb(self):
  4258. """
  4259. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  4260. a new Gerber object.
  4261. :return: None
  4262. """
  4263. self.report_usage("on_edit_join_grb()")
  4264. objs = self.collection.get_selected()
  4265. for obj in objs:
  4266. if not isinstance(obj, FlatCAMGerber):
  4267. self.inform.emit('[ERROR_NOTCL] %s' %
  4268. _("Failed. Gerber joining works only on Gerber objects."))
  4269. return
  4270. if len(objs) < 2:
  4271. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4272. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4273. return 'fail'
  4274. def initialize(obj, app):
  4275. FlatCAMGerber.merge(self, grb_list=objs, grb_final=obj)
  4276. self.new_object("gerber", 'Combo_Gerber', initialize)
  4277. self.should_we_save = True
  4278. def on_convert_singlegeo_to_multigeo(self):
  4279. """
  4280. Called for converting a Geometry object from single-geo to multi-geo.
  4281. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4282. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4283. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4284. the solid-geometry of that tool.
  4285. :return: None
  4286. """
  4287. self.report_usage("on_convert_singlegeo_to_multigeo()")
  4288. obj = self.collection.get_active()
  4289. if obj is None:
  4290. self.inform.emit('[ERROR_NOTCL] %s' %
  4291. _("Failed. Select a Geometry Object and try again."))
  4292. return
  4293. if not isinstance(obj, FlatCAMGeometry):
  4294. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4295. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4296. return
  4297. obj.multigeo = True
  4298. for tooluid, dict_value in obj.tools.items():
  4299. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  4300. if not isinstance(obj.solid_geometry, list):
  4301. obj.solid_geometry = [obj.solid_geometry]
  4302. obj.solid_geometry[:] = []
  4303. obj.plot()
  4304. self.should_we_save = True
  4305. self.inform.emit('[success] %s' %
  4306. _("A Geometry object was converted to MultiGeo type."))
  4307. def on_convert_multigeo_to_singlegeo(self):
  4308. """
  4309. Called for converting a Geometry object from multi-geo to single-geo.
  4310. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4311. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4312. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4313. the solid-geometry of that tool.
  4314. :return: None
  4315. """
  4316. self.report_usage("on_convert_multigeo_to_singlegeo()")
  4317. obj = self.collection.get_active()
  4318. if obj is None:
  4319. self.inform.emit('[ERROR_NOTCL] %s' %
  4320. _("Failed. Select a Geometry Object and try again."))
  4321. return
  4322. if not isinstance(obj, FlatCAMGeometry):
  4323. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4324. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4325. return
  4326. obj.multigeo = False
  4327. total_solid_geometry = []
  4328. for tooluid, dict_value in obj.tools.items():
  4329. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  4330. # clear the original geometry
  4331. dict_value['solid_geometry'][:] = []
  4332. obj.solid_geometry = deepcopy(total_solid_geometry)
  4333. obj.plot()
  4334. self.should_we_save = True
  4335. self.inform.emit('[success] %s' %
  4336. _("A Geometry object was converted to SingleGeo type."))
  4337. def on_options_dict_change(self, field):
  4338. """
  4339. Called whenever a key changed in the self.options dictionary. This dict was used to store the preferences of the
  4340. current project. This feature is no longer used.
  4341. :param field:
  4342. :return:
  4343. """
  4344. self.options_write_form_field(field)
  4345. if field == "units":
  4346. self.set_screen_units(self.options['units'])
  4347. def on_defaults_dict_change(self, field):
  4348. """
  4349. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  4350. Edit -> Preferences tab window.
  4351. :param field: the key of the self.defaults dictionary that was changed.
  4352. :return: None
  4353. """
  4354. self.defaults_write_form_field(field)
  4355. if field == "units":
  4356. self.set_screen_units(self.defaults['units'])
  4357. def set_screen_units(self, units):
  4358. """
  4359. Set the FlatCAM units on the status bar.
  4360. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  4361. :return: None
  4362. """
  4363. self.ui.units_label.setText("[" + units.lower() + "]")
  4364. def on_toggle_units(self, no_pref=False):
  4365. """
  4366. Callback for the Units radio-button change in the Preferences tab.
  4367. Changes the application's default units adn for the project too.
  4368. If changing the project's units, the change propagates to all of
  4369. the objects in the project.
  4370. :return: None
  4371. """
  4372. self.report_usage("on_toggle_units")
  4373. if self.toggle_units_ignore:
  4374. return
  4375. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4376. # If option is the same, then ignore
  4377. if new_units == self.defaults["units"].upper():
  4378. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  4379. return
  4380. # Options to scale
  4381. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  4382. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  4383. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  4384. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  4385. "excellon_z_pdepth",
  4386. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  4387. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  4388. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  4389. "geometry_feedrate_probe",
  4390. 'cncjob_tooldia',
  4391. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  4392. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia"
  4393. "tools_2sided_drilldia", "tools_film_boundary",
  4394. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  4395. "tools_panelize_constrainx", "tools_panelize_constrainy",
  4396. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  4397. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  4398. "tools_transform_offset_y",
  4399. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  4400. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  4401. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  4402. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  4403. 'global_gridx', 'global_gridy', 'global_snap_max']
  4404. def scale_options(sfactor):
  4405. for dim in dimensions:
  4406. if dim == 'excellon_toolchangexy':
  4407. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4408. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4409. coords_xy[0] *= sfactor
  4410. coords_xy[1] *= sfactor
  4411. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4412. elif dim == 'geometry_toolchangexy':
  4413. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4414. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4415. coords_xy[0] *= sfactor
  4416. coords_xy[1] *= sfactor
  4417. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4418. elif dim == 'geometry_cnctooldia':
  4419. tools_diameters = []
  4420. try:
  4421. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4422. tools_diameters = [eval(a) for a in tools_string if a != '']
  4423. except Exception as e:
  4424. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4425. self.options['geometry_cnctooldia'] = ''
  4426. for t in range(len(tools_diameters)):
  4427. tools_diameters[t] *= sfactor
  4428. self.options['geometry_cnctooldia'] += "%f," % tools_diameters[t]
  4429. elif dim == 'tools_ncctools':
  4430. ncctools = []
  4431. try:
  4432. tools_string = self.defaults["tools_ncctools"].split(",")
  4433. ncctools = [eval(a) for a in tools_string if a != '']
  4434. except Exception as e:
  4435. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4436. self.options['tools_ncctools'] = ''
  4437. for t in range(len(ncctools)):
  4438. ncctools[t] *= sfactor
  4439. self.options['tools_ncctools'] += "%f," % ncctools[t]
  4440. elif dim == 'tools_solderpaste_tools':
  4441. sptools = []
  4442. try:
  4443. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4444. sptools = [eval(a) for a in tools_string if a != '']
  4445. except Exception as e:
  4446. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4447. self.options['tools_solderpaste_tools'] = ""
  4448. for t in range(len(sptools)):
  4449. sptools[t] *= sfactor
  4450. self.options['tools_solderpaste_tools'] += "%f," % sptools[t]
  4451. elif dim == 'tools_solderpaste_xy_toolchange':
  4452. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4453. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4454. sp_coords[0] *= sfactor
  4455. sp_coords[1] *= sfactor
  4456. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  4457. elif dim == 'global_gridx' or dim == 'global_gridy':
  4458. if new_units == 'IN':
  4459. val = 0.1
  4460. try:
  4461. val = float(self.defaults[dim]) * sfactor
  4462. except Exception as e:
  4463. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4464. self.options[dim] = float('%.6f' % val)
  4465. else:
  4466. val = 0.1
  4467. try:
  4468. val = float(self.defaults[dim]) * sfactor
  4469. except Exception as e:
  4470. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4471. self.options[dim] = float('%.4f' % val)
  4472. else:
  4473. val = 0.1
  4474. try:
  4475. val = float(self.options[dim]) * sfactor
  4476. except Exception as e:
  4477. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  4478. self.options[dim] = val
  4479. def scale_defaults(sfactor):
  4480. for dim in dimensions:
  4481. if dim == 'excellon_toolchangexy':
  4482. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4483. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4484. coords_xy[0] *= sfactor
  4485. coords_xy[1] *= sfactor
  4486. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4487. elif dim == 'geometry_toolchangexy':
  4488. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4489. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4490. coords_xy[0] *= sfactor
  4491. coords_xy[1] *= sfactor
  4492. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4493. elif dim == 'geometry_cnctooldia':
  4494. tools_diameters = []
  4495. try:
  4496. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4497. tools_diameters = [eval(a) for a in tools_string if a != '']
  4498. except Exception as e:
  4499. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4500. self.defaults['geometry_cnctooldia'] = ''
  4501. for t in range(len(tools_diameters)):
  4502. tools_diameters[t] *= sfactor
  4503. self.defaults['geometry_cnctooldia'] += "%.4f," % tools_diameters[t]
  4504. elif dim == 'tools_ncctools':
  4505. ncctools = []
  4506. try:
  4507. tools_string = self.defaults["tools_ncctools"].split(",")
  4508. ncctools = [eval(a) for a in tools_string if a != '']
  4509. except Exception as e:
  4510. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4511. self.defaults['tools_ncctools'] = ''
  4512. for t in range(len(ncctools)):
  4513. ncctools[t] *= sfactor
  4514. self.defaults['tools_ncctools'] += "%.4f," % ncctools[t]
  4515. elif dim == 'tools_solderpaste_tools':
  4516. sptools = []
  4517. try:
  4518. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4519. sptools = [eval(a) for a in tools_string if a != '']
  4520. except Exception as e:
  4521. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4522. self.defaults['tools_solderpaste_tools'] = ""
  4523. for t in range(len(sptools)):
  4524. sptools[t] *= sfactor
  4525. self.defaults['tools_solderpaste_tools'] += "%.4f," % sptools[t]
  4526. elif dim == 'tools_solderpaste_xy_toolchange':
  4527. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4528. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4529. sp_coords[0] *= sfactor
  4530. sp_coords[1] *= sfactor
  4531. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  4532. elif dim == 'global_gridx' or dim == 'global_gridy':
  4533. if new_units == 'IN':
  4534. val = 0.1
  4535. try:
  4536. val = float(self.defaults[dim]) * sfactor
  4537. except Exception as e:
  4538. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4539. self.defaults[dim] = float('%.6f' % val)
  4540. else:
  4541. val = 0.1
  4542. try:
  4543. val = float(self.defaults[dim]) * sfactor
  4544. except Exception as e:
  4545. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4546. self.defaults[dim] = float('%.4f' % val)
  4547. else:
  4548. val = 0.1
  4549. try:
  4550. val = float(self.defaults[dim]) * sfactor
  4551. except Exception as e:
  4552. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4553. self.defaults[dim] = val
  4554. # The scaling factor depending on choice of units.
  4555. factor = 1/25.4
  4556. if new_units == 'MM':
  4557. factor = 25.4
  4558. # Changing project units. Warn user.
  4559. msgbox = QtWidgets.QMessageBox()
  4560. msgbox.setWindowTitle(_("Toggle Units"))
  4561. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  4562. msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4563. msgbox.setInformativeText(_("Changing the units of the project causes all geometrical "
  4564. "properties of all objects to be scaled accordingly.\nContinue?"))
  4565. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4566. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4567. msgbox.setDefaultButton(bt_ok)
  4568. msgbox.exec_()
  4569. response = msgbox.clickedButton()
  4570. if response == bt_ok:
  4571. if no_pref is False:
  4572. self.options_read_form()
  4573. scale_options(factor)
  4574. self.options_write_form()
  4575. self.defaults_read_form()
  4576. scale_defaults(factor)
  4577. self.defaults_write_form(fl_units=new_units)
  4578. # save the defaults to file, some may assume that the conversion is enough and it's not
  4579. self.on_save_button()
  4580. self.should_we_save = True
  4581. # change this only if the workspace is active
  4582. if self.defaults['global_workspace'] is True:
  4583. self.plotcanvas.draw_workspace()
  4584. # adjust the grid values on the main toolbar
  4585. dec = 6 if new_units == 'IN'else 4
  4586. val_x = float(self.ui.grid_gap_x_entry.get_value()) * factor
  4587. self.ui.grid_gap_x_entry.set_value(val_x, decimals=dec)
  4588. if not self.ui.grid_gap_link_cb.isChecked():
  4589. val_y = float(self.ui.grid_gap_y_entry.get_value()) * factor
  4590. self.ui.grid_gap_y_entry.set_value(val_y, decimals=dec)
  4591. for obj in self.collection.get_list():
  4592. obj.convert_units(new_units)
  4593. # make that the properties stored in the object are also updated
  4594. self.object_changed.emit(obj)
  4595. obj.build_ui()
  4596. current = self.collection.get_active()
  4597. if current is not None:
  4598. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  4599. if not isinstance(current, FlatCAMGeometry):
  4600. current.to_form()
  4601. self.plot_all()
  4602. self.inform.emit('[success] %s: %s' %
  4603. (_("Converted units to"), new_units))
  4604. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  4605. self.set_screen_units(new_units)
  4606. else:
  4607. # Undo toggling
  4608. self.toggle_units_ignore = True
  4609. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4610. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  4611. else:
  4612. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  4613. self.toggle_units_ignore = False
  4614. self.inform.emit('[WARNING_NOTCL]%s' %
  4615. _(" Units conversion cancelled."))
  4616. self.options_read_form()
  4617. self.defaults_read_form()
  4618. def on_toggle_units_click(self):
  4619. try:
  4620. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  4621. except (TypeError, AttributeError):
  4622. pass
  4623. if self.defaults["units"] == 'MM':
  4624. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  4625. else:
  4626. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  4627. self.on_toggle_units(no_pref=True)
  4628. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  4629. lambda: self.on_toggle_units(no_pref=False))
  4630. def on_fullscreen(self):
  4631. self.report_usage("on_fullscreen()")
  4632. if self.toggle_fscreen is False:
  4633. if sys.platform == 'win32':
  4634. self.ui.showFullScreen()
  4635. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  4636. tb.setVisible(False)
  4637. self.ui.splitter_left.setVisible(False)
  4638. self.toggle_fscreen = True
  4639. else:
  4640. if sys.platform == 'win32':
  4641. self.ui.showNormal()
  4642. self.restore_toolbar_view()
  4643. self.ui.splitter_left.setVisible(True)
  4644. self.toggle_fscreen = False
  4645. def on_toggle_plotarea(self):
  4646. self.report_usage("on_toggle_plotarea()")
  4647. try:
  4648. name = self.ui.plot_tab_area.widget(0).objectName()
  4649. except AttributeError:
  4650. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4651. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4652. self.ui.plot_tab_area.protectTab(0)
  4653. return
  4654. if name != 'plotarea':
  4655. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  4656. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4657. self.ui.plot_tab_area.protectTab(0)
  4658. else:
  4659. self.ui.plot_tab_area.closeTab(0)
  4660. def on_toggle_notebook(self):
  4661. if self.ui.splitter.sizes()[0] == 0:
  4662. self.ui.splitter.setSizes([1, 1])
  4663. else:
  4664. self.ui.splitter.setSizes([0, 1])
  4665. def on_toggle_axis(self):
  4666. self.report_usage("on_toggle_axis()")
  4667. if self.toggle_axis is False:
  4668. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4669. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4670. self.plotcanvas.redraw()
  4671. self.toggle_axis = True
  4672. else:
  4673. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4674. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4675. self.plotcanvas.redraw()
  4676. self.toggle_axis = False
  4677. def on_toggle_grid(self):
  4678. self.report_usage("on_toggle_grid()")
  4679. self.ui.grid_snap_btn.trigger()
  4680. def on_options_combo_change(self, sel):
  4681. """
  4682. Called when the combo box to choose between application defaults and
  4683. project option changes value. The corresponding variables are
  4684. copied to the UI.
  4685. :param sel: The option index that was chosen.
  4686. :return: None
  4687. """
  4688. # combo_sel = self.ui.notebook.combo_options.get_active()
  4689. App.log.debug("Options --> %s" % sel)
  4690. # form = [self.defaults_form, self.options_form][sel]
  4691. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  4692. if sel == 0:
  4693. self.gen_form = self.ui.general_defaults_form
  4694. self.ger_form = self.ui.gerber_defaults_form
  4695. self.exc_form = self.ui.excellon_defaults_form
  4696. self.geo_form = self.ui.geometry_defaults_form
  4697. self.cnc_form = self.ui.cncjob_defaults_form
  4698. self.tools_form = self.ui.tools_defaults_form
  4699. self.fa_form = self.ui.util_defaults_form
  4700. elif sel == 1:
  4701. self.gen_form = self.ui.general_options_form
  4702. self.ger_form = self.ui.gerber_options_form
  4703. self.exc_form = self.ui.excellon_options_form
  4704. self.geo_form = self.ui.geometry_options_form
  4705. self.cnc_form = self.ui.cncjob_options_form
  4706. self.tools_form = self.ui.tools_options_form
  4707. self.fa_form = self.ui.util_options_form
  4708. else:
  4709. return
  4710. try:
  4711. self.ui.general_scroll_area.takeWidget()
  4712. except:
  4713. self.log.debug("Nothing to remove")
  4714. self.ui.general_scroll_area.setWidget(self.gen_form)
  4715. self.gen_form.show()
  4716. try:
  4717. self.ui.gerber_scroll_area.takeWidget()
  4718. except:
  4719. self.log.debug("Nothing to remove")
  4720. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  4721. self.ger_form.show()
  4722. try:
  4723. self.ui.excellon_scroll_area.takeWidget()
  4724. except:
  4725. self.log.debug("Nothing to remove")
  4726. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  4727. self.exc_form.show()
  4728. try:
  4729. self.ui.geometry_scroll_area.takeWidget()
  4730. except:
  4731. self.log.debug("Nothing to remove")
  4732. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  4733. self.geo_form.show()
  4734. try:
  4735. self.ui.cncjob_scroll_area.takeWidget()
  4736. except:
  4737. self.log.debug("Nothing to remove")
  4738. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  4739. self.cnc_form.show()
  4740. try:
  4741. self.ui.tools_scroll_area.takeWidget()
  4742. except:
  4743. self.log.debug("Nothing to remove")
  4744. self.ui.tools_scroll_area.setWidget(self.tools_form)
  4745. self.tools_form.show()
  4746. try:
  4747. self.ui.fa_scroll_area.takeWidget()
  4748. except:
  4749. self.log.debug("Nothing to remove")
  4750. self.ui.fa_scroll_area.setWidget(self.fa_form)
  4751. self.fa_form.show()
  4752. self.log.debug("Finished GUI form initialization.")
  4753. # self.options2form()
  4754. def on_excellon_defaults_button(self):
  4755. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  4756. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  4757. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  4758. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  4759. self.defaults_form_fields["excellon_zeros"].set_value('L')
  4760. self.defaults_form_fields["excellon_units"].set_value('INCH')
  4761. log.debug("Excellon app defaults loaded ...")
  4762. def on_excellon_options_button(self):
  4763. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  4764. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  4765. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  4766. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  4767. self.options_form_fields["excellon_zeros"].set_value('L')
  4768. self.options_form_fields["excellon_units"].set_value('INCH')
  4769. log.debug("Excellon options defaults loaded ...")
  4770. def on_update_exc_export(self, state):
  4771. """
  4772. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  4773. if the update_excellon_cb checkbox is checked
  4774. :param state: state of the checkbox whose signals is tied to his slot
  4775. :return:
  4776. """
  4777. if state:
  4778. # first try to disconnect
  4779. try:
  4780. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged.\
  4781. disconnect(self.on_excellon_format_changed)
  4782. except TypeError:
  4783. pass
  4784. try:
  4785. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged.\
  4786. disconnect(self.on_excellon_format_changed)
  4787. except TypeError:
  4788. pass
  4789. try:
  4790. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged.\
  4791. disconnect(self.on_excellon_format_changed)
  4792. except TypeError:
  4793. pass
  4794. try:
  4795. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged.\
  4796. disconnect(self.on_excellon_format_changed)
  4797. except TypeError:
  4798. pass
  4799. try:
  4800. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.\
  4801. disconnect(self.on_excellon_zeros_changed)
  4802. except TypeError:
  4803. pass
  4804. try:
  4805. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.\
  4806. disconnect(self.on_excellon_zeros_changed)
  4807. except TypeError:
  4808. pass
  4809. # the connect them
  4810. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged.connect(
  4811. self.on_excellon_format_changed)
  4812. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged.connect(
  4813. self.on_excellon_format_changed)
  4814. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged.connect(
  4815. self.on_excellon_format_changed)
  4816. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged.connect(
  4817. self.on_excellon_format_changed)
  4818. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  4819. self.on_excellon_zeros_changed)
  4820. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  4821. self.on_excellon_units_changed)
  4822. else:
  4823. # disconnect the signals
  4824. try:
  4825. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged. \
  4826. disconnect(self.on_excellon_format_changed)
  4827. except TypeError:
  4828. pass
  4829. try:
  4830. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged. \
  4831. disconnect(self.on_excellon_format_changed)
  4832. except TypeError:
  4833. pass
  4834. try:
  4835. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged. \
  4836. disconnect(self.on_excellon_format_changed)
  4837. except TypeError:
  4838. pass
  4839. try:
  4840. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged. \
  4841. disconnect(self.on_excellon_format_changed)
  4842. except TypeError:
  4843. pass
  4844. try:
  4845. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  4846. disconnect(self.on_excellon_zeros_changed)
  4847. except TypeError:
  4848. pass
  4849. try:
  4850. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  4851. disconnect(self.on_excellon_zeros_changed)
  4852. except TypeError:
  4853. pass
  4854. def on_excellon_format_changed(self):
  4855. """
  4856. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  4857. :return: None
  4858. """
  4859. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  4860. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  4861. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  4862. )
  4863. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  4864. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  4865. )
  4866. else:
  4867. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  4868. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  4869. )
  4870. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  4871. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  4872. )
  4873. def on_excellon_zeros_changed(self):
  4874. """
  4875. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  4876. :return: None
  4877. """
  4878. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  4879. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  4880. )
  4881. def on_excellon_units_changed(self):
  4882. """
  4883. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  4884. :return: None
  4885. """
  4886. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  4887. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  4888. )
  4889. self.on_excellon_format_changed()
  4890. # Setting plot colors handlers
  4891. def on_pf_color_entry(self):
  4892. self.defaults['global_plot_fill'] = \
  4893. self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  4894. self.defaults['global_plot_fill'][7:9]
  4895. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  4896. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  4897. def on_pf_color_button(self):
  4898. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  4899. c_dialog = QtWidgets.QColorDialog()
  4900. plot_fill_color = c_dialog.getColor(initial=current_color)
  4901. if plot_fill_color.isValid() is False:
  4902. return
  4903. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  4904. "background-color:%s" % str(plot_fill_color.name()))
  4905. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  4906. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  4907. self.defaults['global_plot_fill'] = new_val
  4908. def on_pf_color_spinner(self):
  4909. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  4910. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  4911. self.defaults['global_plot_fill'] = \
  4912. self.defaults['global_plot_fill'][:7] + \
  4913. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4914. self.defaults['global_plot_line'] = \
  4915. self.defaults['global_plot_line'][:7] + \
  4916. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4917. def on_pf_color_slider(self):
  4918. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  4919. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  4920. def on_pl_color_entry(self):
  4921. self.defaults['global_plot_line'] = \
  4922. self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  4923. self.defaults['global_plot_line'][7:9]
  4924. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  4925. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  4926. def on_pl_color_button(self):
  4927. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  4928. # print(current_color)
  4929. c_dialog = QtWidgets.QColorDialog()
  4930. plot_line_color = c_dialog.getColor(initial=current_color)
  4931. if plot_line_color.isValid() is False:
  4932. return
  4933. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  4934. "background-color:%s" % str(plot_line_color.name()))
  4935. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  4936. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  4937. self.defaults['global_plot_line'] = new_val_line
  4938. # Setting selection colors (left - right) handlers
  4939. def on_sf_color_entry(self):
  4940. self.defaults['global_sel_fill'] = \
  4941. self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  4942. self.defaults['global_sel_fill'][7:9]
  4943. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  4944. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  4945. def on_sf_color_button(self):
  4946. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  4947. c_dialog = QtWidgets.QColorDialog()
  4948. plot_fill_color = c_dialog.getColor(initial=current_color)
  4949. if plot_fill_color.isValid() is False:
  4950. return
  4951. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  4952. "background-color:%s" % str(plot_fill_color.name()))
  4953. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  4954. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  4955. self.defaults['global_sel_fill'] = new_val
  4956. def on_sf_color_spinner(self):
  4957. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  4958. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  4959. self.defaults['global_sel_fill'] = \
  4960. self.defaults['global_sel_fill'][:7] + \
  4961. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4962. self.defaults['global_sel_line'] = \
  4963. self.defaults['global_sel_line'][:7] + \
  4964. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4965. def on_sf_color_slider(self):
  4966. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  4967. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  4968. def on_sl_color_entry(self):
  4969. self.defaults['global_sel_line'] = \
  4970. self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  4971. self.defaults['global_sel_line'][7:9]
  4972. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  4973. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  4974. def on_sl_color_button(self):
  4975. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  4976. c_dialog = QtWidgets.QColorDialog()
  4977. plot_line_color = c_dialog.getColor(initial=current_color)
  4978. if plot_line_color.isValid() is False:
  4979. return
  4980. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  4981. "background-color:%s" % str(plot_line_color.name()))
  4982. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  4983. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  4984. self.defaults['global_sel_line'] = new_val_line
  4985. # Setting selection colors (right - left) handlers
  4986. def on_alt_sf_color_entry(self):
  4987. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  4988. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  4989. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  4990. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  4991. def on_alt_sf_color_button(self):
  4992. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  4993. c_dialog = QtWidgets.QColorDialog()
  4994. plot_fill_color = c_dialog.getColor(initial=current_color)
  4995. if plot_fill_color.isValid() is False:
  4996. return
  4997. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  4998. "background-color:%s" % str(plot_fill_color.name()))
  4999. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  5000. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  5001. self.defaults['global_alt_sel_fill'] = new_val
  5002. def on_alt_sf_color_spinner(self):
  5003. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  5004. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  5005. self.defaults['global_alt_sel_fill'] = \
  5006. self.defaults['global_alt_sel_fill'][:7] + \
  5007. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5008. self.defaults['global_alt_sel_line'] = \
  5009. self.defaults['global_alt_sel_line'][:7] + \
  5010. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5011. def on_alt_sf_color_slider(self):
  5012. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  5013. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  5014. def on_alt_sl_color_entry(self):
  5015. self.defaults['global_alt_sel_line'] = \
  5016. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  5017. self.defaults['global_alt_sel_line'][7:9]
  5018. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5019. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  5020. def on_alt_sl_color_button(self):
  5021. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  5022. c_dialog = QtWidgets.QColorDialog()
  5023. plot_line_color = c_dialog.getColor(initial=current_color)
  5024. if plot_line_color.isValid() is False:
  5025. return
  5026. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5027. "background-color:%s" % str(plot_line_color.name()))
  5028. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  5029. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  5030. self.defaults['global_alt_sel_line'] = new_val_line
  5031. # Setting Editor colors
  5032. def on_draw_color_entry(self):
  5033. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5034. .draw_color_entry.get_value()
  5035. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5036. "background-color:%s" % str(self.defaults['global_draw_color']))
  5037. def on_draw_color_button(self):
  5038. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  5039. c_dialog = QtWidgets.QColorDialog()
  5040. draw_color = c_dialog.getColor(initial=current_color)
  5041. if draw_color.isValid() is False:
  5042. return
  5043. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5044. "background-color:%s" % str(draw_color.name()))
  5045. new_val = str(draw_color.name())
  5046. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  5047. self.defaults['global_draw_color'] = new_val
  5048. def on_sel_draw_color_entry(self):
  5049. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5050. .sel_draw_color_entry.get_value()
  5051. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5052. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  5053. def on_sel_draw_color_button(self):
  5054. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  5055. c_dialog = QtWidgets.QColorDialog()
  5056. sel_draw_color = c_dialog.getColor(initial=current_color)
  5057. if sel_draw_color.isValid() is False:
  5058. return
  5059. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5060. "background-color:%s" % str(sel_draw_color.name()))
  5061. new_val_sel = str(sel_draw_color.name())
  5062. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  5063. self.defaults['global_sel_draw_color'] = new_val_sel
  5064. def on_proj_color_entry(self):
  5065. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  5066. .proj_color_entry.get_value()
  5067. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5068. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  5069. def on_proj_color_button(self):
  5070. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  5071. c_dialog = QtWidgets.QColorDialog()
  5072. proj_color = c_dialog.getColor(initial=current_color)
  5073. if proj_color.isValid() is False:
  5074. return
  5075. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5076. "background-color:%s" % str(proj_color.name()))
  5077. new_val_sel = str(proj_color.name())
  5078. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  5079. self.defaults['global_proj_item_color'] = new_val_sel
  5080. def on_proj_color_dis_entry(self):
  5081. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  5082. .proj_color_dis_entry.get_value()
  5083. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5084. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  5085. def on_proj_color_dis_button(self):
  5086. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  5087. c_dialog = QtWidgets.QColorDialog()
  5088. proj_color = c_dialog.getColor(initial=current_color)
  5089. if proj_color.isValid() is False:
  5090. return
  5091. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5092. "background-color:%s" % str(proj_color.name()))
  5093. new_val_sel = str(proj_color.name())
  5094. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  5095. self.defaults['global_proj_item_dis_color'] = new_val_sel
  5096. def on_annotation_fontcolor_entry(self):
  5097. self.defaults['cncjob_annotation_fontcolor'] = \
  5098. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.get_value()
  5099. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5100. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  5101. def on_annotation_fontcolor_button(self):
  5102. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  5103. c_dialog = QtWidgets.QColorDialog()
  5104. annotation_color = c_dialog.getColor(initial=current_color)
  5105. if annotation_color.isValid() is False:
  5106. return
  5107. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5108. "background-color:%s" % str(annotation_color.name()))
  5109. new_val_sel = str(annotation_color.name())
  5110. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(new_val_sel)
  5111. self.defaults['cncjob_annotation_fontcolor'] = new_val_sel
  5112. def on_film_color_entry(self):
  5113. self.defaults['tools_film_color'] = \
  5114. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  5115. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5116. "background-color:%s" % str(self.defaults['tools_film_color']))
  5117. def on_film_color_button(self):
  5118. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  5119. c_dialog = QtWidgets.QColorDialog()
  5120. film_color = c_dialog.getColor(initial=current_color)
  5121. if film_color.isValid() is False:
  5122. return
  5123. # if new color is different then mark that the Preferences are changed
  5124. if film_color != current_color:
  5125. self.on_preferences_edited()
  5126. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5127. "background-color:%s" % str(film_color.name()))
  5128. new_val_sel = str(film_color.name())
  5129. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  5130. self.defaults['tools_film_color'] = new_val_sel
  5131. def on_splash_changed(self, state):
  5132. settings = QSettings("Open Source", "FlatCAM")
  5133. settings.setValue('splash_screen', 1) if state else settings.setValue('splash_screen', 0)
  5134. # This will write the setting to the platform specific storage.
  5135. del settings
  5136. def on_notebook_tab_rmb_click(self, checked):
  5137. self.ui.notebook.set_detachable(val=checked)
  5138. self.defaults["global_tabs_detachable"] = checked
  5139. self.ui.plot_tab_area.set_detachable(val=checked)
  5140. self.defaults["global_tabs_detachable"] = checked
  5141. def on_deselect_all(self):
  5142. self.collection.set_all_inactive()
  5143. self.delete_selection_shape()
  5144. def on_workspace_modified(self):
  5145. self.save_defaults(silent=True)
  5146. self.plotcanvas.draw_workspace()
  5147. def on_workspace(self):
  5148. self.report_usage("on_workspace()")
  5149. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  5150. self.plotcanvas.restore_workspace()
  5151. else:
  5152. self.plotcanvas.delete_workspace()
  5153. self.save_defaults(silent=True)
  5154. def on_workspace_menu(self):
  5155. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  5156. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  5157. else:
  5158. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  5159. self.on_workspace()
  5160. def on_layout(self, index=None, lay=None):
  5161. self.report_usage("on_layout()")
  5162. if lay:
  5163. current_layout = lay
  5164. else:
  5165. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  5166. settings = QSettings("Open Source", "FlatCAM")
  5167. settings.setValue('layout', current_layout)
  5168. # This will write the setting to the platform specific storage.
  5169. del settings
  5170. # first remove the toolbars:
  5171. try:
  5172. self.ui.removeToolBar(self.ui.toolbarfile)
  5173. self.ui.removeToolBar(self.ui.toolbargeo)
  5174. self.ui.removeToolBar(self.ui.toolbarview)
  5175. self.ui.removeToolBar(self.ui.toolbarshell)
  5176. self.ui.removeToolBar(self.ui.toolbartools)
  5177. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  5178. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  5179. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  5180. self.ui.removeToolBar(self.ui.snap_toolbar)
  5181. self.ui.removeToolBar(self.ui.toolbarshell)
  5182. except Exception as e:
  5183. pass
  5184. if current_layout == 'standard':
  5185. # ## TOOLBAR INSTALLATION # ##
  5186. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5187. self.ui.toolbarfile.setObjectName('File_TB')
  5188. self.ui.addToolBar(self.ui.toolbarfile)
  5189. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5190. self.ui.toolbargeo.setObjectName('Edit_TB')
  5191. self.ui.addToolBar(self.ui.toolbargeo)
  5192. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5193. self.ui.toolbarview.setObjectName('View_TB')
  5194. self.ui.addToolBar(self.ui.toolbarview)
  5195. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5196. self.ui.toolbarshell.setObjectName('Shell_TB')
  5197. self.ui.addToolBar(self.ui.toolbarshell)
  5198. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5199. self.ui.toolbartools.setObjectName('Tools_TB')
  5200. self.ui.addToolBar(self.ui.toolbartools)
  5201. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5202. # self.ui.exc_edit_toolbar.setVisible(False)
  5203. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5204. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  5205. self.ui.addToolBarBreak()
  5206. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5207. # self.ui.geo_edit_toolbar.setVisible(False)
  5208. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5209. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  5210. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5211. # self.ui.grb_edit_toolbar.setVisible(False)
  5212. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5213. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  5214. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5215. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5216. # self.ui.snap_toolbar.setMaximumHeight(30)
  5217. self.ui.addToolBar(self.ui.snap_toolbar)
  5218. self.ui.corner_snap_btn.setVisible(False)
  5219. self.ui.snap_magnet.setVisible(False)
  5220. elif current_layout == 'compact':
  5221. # ## TOOLBAR INSTALLATION # ##
  5222. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5223. self.ui.toolbarfile.setObjectName('File_TB')
  5224. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  5225. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5226. self.ui.toolbargeo.setObjectName('Edit_TB')
  5227. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  5228. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5229. self.ui.toolbarshell.setObjectName('Shell_TB')
  5230. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  5231. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5232. self.ui.toolbartools.setObjectName('Tools_TB')
  5233. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  5234. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5235. # self.ui.geo_edit_toolbar.setVisible(False)
  5236. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5237. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  5238. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5239. self.ui.toolbarview.setObjectName('View_TB')
  5240. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.toolbarview)
  5241. self.ui.addToolBarBreak(area=Qt.RightToolBarArea)
  5242. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5243. # self.ui.grb_edit_toolbar.setVisible(False)
  5244. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5245. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  5246. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5247. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5248. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  5249. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5250. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5251. self.ui.snap_toolbar.setMaximumHeight(30)
  5252. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  5253. self.ui.corner_snap_btn.setVisible(True)
  5254. self.ui.snap_magnet.setVisible(True)
  5255. # add all the actions to the toolbars
  5256. self.ui.populate_toolbars()
  5257. # reconnect all the signals to the toolbar actions
  5258. self.connect_toolbar_signals()
  5259. self.ui.grid_snap_btn.setChecked(True)
  5260. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  5261. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  5262. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  5263. self.ui.grid_gap_link_cb.setChecked(True)
  5264. def on_cnc_custom_parameters(self, signal_text):
  5265. if signal_text == 'Parameters':
  5266. return
  5267. else:
  5268. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  5269. def on_save_button(self):
  5270. log.debug("App.on_save_button() --> Saving preferences to file.")
  5271. self.preferences_changed_flag = False
  5272. self.save_defaults(silent=False)
  5273. # load the defaults so they are updated into the app
  5274. self.load_defaults(filename='current_defaults')
  5275. # Re-fresh project options
  5276. self.on_options_app2project()
  5277. settings = QSettings("Open Source", "FlatCAM")
  5278. # save the notebook font size
  5279. fsize = self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  5280. settings.setValue('notebook_font_size', fsize)
  5281. # save the axis font size
  5282. g_fsize = self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  5283. settings.setValue('axis_font_size', g_fsize)
  5284. # save the textbox font size
  5285. tb_fsize = self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  5286. settings.setValue('textbox_font_size', tb_fsize)
  5287. # This will write the setting to the platform specific storage.
  5288. del settings
  5289. def handlePrint(self):
  5290. self.report_usage("handlePrint()")
  5291. dialog = QtPrintSupport.QPrintDialog()
  5292. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  5293. self.ui.code_editor.document().print_(dialog.printer())
  5294. def handlePreview(self):
  5295. self.report_usage("handlePreview()")
  5296. dialog = QtPrintSupport.QPrintPreviewDialog()
  5297. dialog.paintRequested.connect(self.ui.code_editor.print_)
  5298. dialog.exec_()
  5299. def handleTextChanged(self):
  5300. # enable = not self.ui.code_editor.document().isEmpty()
  5301. # self.ui.buttonPrint.setEnabled(enable)
  5302. # self.ui.buttonPreview.setEnabled(enable)
  5303. pass
  5304. def handleOpen(self, filt=None):
  5305. self.report_usage("handleOpen()")
  5306. if filt:
  5307. _filter_ = filt
  5308. else:
  5309. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  5310. "All Files (*.*)"
  5311. path, _f = QtWidgets.QFileDialog.getOpenFileName(
  5312. caption=_('Open file'), directory=self.get_last_folder(), filter=_filter_)
  5313. if path:
  5314. file = QtCore.QFile(path)
  5315. if file.open(QtCore.QIODevice.ReadOnly):
  5316. stream = QtCore.QTextStream(file)
  5317. self.gcode_edited = stream.readAll()
  5318. self.ui.code_editor.setPlainText(self.gcode_edited)
  5319. file.close()
  5320. def handleSaveGCode(self, name=None, filt=None):
  5321. self.report_usage("handleSaveGCode()")
  5322. if filt:
  5323. _filter_ = filt
  5324. else:
  5325. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  5326. "All Files (*.*)"
  5327. if name:
  5328. obj_name = name
  5329. else:
  5330. try:
  5331. obj_name = self.collection.get_active().options['name']
  5332. except AttributeError:
  5333. obj_name = 'file'
  5334. if filt is None:
  5335. _filter_ = "FlatConfig Files (*.FlatConfig);;All Files (*.*)"
  5336. try:
  5337. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  5338. caption=_("Export G-Code ..."),
  5339. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  5340. filter=_filter_
  5341. )[0])
  5342. except TypeError:
  5343. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption=_("Export G-Code ..."), filter=_filter_)[0])
  5344. if filename == "":
  5345. self.inform.emit('[WARNING_NOTCL] %s' %
  5346. _("Export Code cancelled."))
  5347. return
  5348. else:
  5349. try:
  5350. my_gcode = self.ui.code_editor.toPlainText()
  5351. with open(filename, 'w') as f:
  5352. for line in my_gcode:
  5353. f.write(line)
  5354. except FileNotFoundError:
  5355. self.inform.emit('[WARNING] %s' %
  5356. _("No such file or directory"))
  5357. return
  5358. except PermissionError:
  5359. self.inform.emit('[WARNING] %s' %
  5360. _("Permission denied, saving not possible.\n"
  5361. "Most likely another app is holding the file open and not accessible."))
  5362. return
  5363. # Just for adding it to the recent files list.
  5364. if self.defaults["global_open_style"] is False:
  5365. self.file_opened.emit("cncjob", filename)
  5366. self.file_saved.emit("cncjob", filename)
  5367. self.inform.emit('%s: %s' % (_("Saved to"), str(filename)))
  5368. def handleFindGCode(self):
  5369. self.report_usage("handleFindGCode()")
  5370. flags = QtGui.QTextDocument.FindCaseSensitively
  5371. text_to_be_found = self.ui.entryFind.get_value()
  5372. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  5373. if r is False:
  5374. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5375. def handleReplaceGCode(self):
  5376. self.report_usage("handleReplaceGCode()")
  5377. old = self.ui.entryFind.get_value()
  5378. new = self.ui.entryReplace.get_value()
  5379. if self.ui.sel_all_cb.isChecked():
  5380. while True:
  5381. cursor = self.ui.code_editor.textCursor()
  5382. cursor.beginEditBlock()
  5383. flags = QtGui.QTextDocument.FindCaseSensitively
  5384. # self.ui.editor is the QPlainTextEdit
  5385. r = self.ui.code_editor.find(str(old), flags)
  5386. if r:
  5387. qc = self.ui.code_editor.textCursor()
  5388. if qc.hasSelection():
  5389. qc.insertText(new)
  5390. else:
  5391. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5392. break
  5393. # Mark end of undo block
  5394. cursor.endEditBlock()
  5395. else:
  5396. cursor = self.ui.code_editor.textCursor()
  5397. cursor.beginEditBlock()
  5398. qc = self.ui.code_editor.textCursor()
  5399. if qc.hasSelection():
  5400. qc.insertText(new)
  5401. # Mark end of undo block
  5402. cursor.endEditBlock()
  5403. def handleRunCode(self):
  5404. # trying to run a Tcl command without having the Shell open will create some warnings because the Tcl Shell
  5405. # tries to print on a hidden widget, therefore show the dock if hidden
  5406. if self.ui.shell_dock.isHidden():
  5407. self.ui.shell_dock.show()
  5408. self.script_code = deepcopy(self.ui.code_editor.toPlainText())
  5409. # self.shell._sysShell.exec_command(script_code)
  5410. old_line = ''
  5411. for tcl_command_line in self.script_code.splitlines():
  5412. # do not process lines starting with '#' = comment and empty lines
  5413. if not tcl_command_line.startswith('#') and tcl_command_line != '':
  5414. # id FlatCAM is run in Windows then replace all the slashes with
  5415. # the UNIX style slash that TCL understands
  5416. if sys.platform == 'win32':
  5417. if "open" in tcl_command_line:
  5418. tcl_command_line = tcl_command_line.replace('\\', '/')
  5419. if old_line != '':
  5420. new_command = old_line + tcl_command_line + '\n'
  5421. else:
  5422. new_command = tcl_command_line
  5423. # execute the actual Tcl command
  5424. try:
  5425. self.shell.open_proccessing() # Disables input box.
  5426. result = self.tcl.eval(str(new_command))
  5427. if result != 'None':
  5428. self.shell.append_output(result + '\n')
  5429. old_line = ''
  5430. except tk.TclError:
  5431. old_line = old_line + tcl_command_line + '\n'
  5432. except Exception as e:
  5433. log.debug("App.handleRunCode() --> %s" % str(e))
  5434. if old_line != '':
  5435. # it means that the script finished with an error
  5436. result = self.tcl.eval("set errorInfo")
  5437. self.log.error("Exec command Exception: %s" % (result + '\n'))
  5438. self.shell.append_error('ERROR: ' + result + '\n')
  5439. self.shell.close_proccessing()
  5440. def on_tool_add_keypress(self):
  5441. # ## Current application units in Upper Case
  5442. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5443. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5444. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5445. if notebook_widget_name == 'selected_tab':
  5446. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5447. # Tool add works for Geometry only if Advanced is True in Preferences
  5448. if self.defaults["global_app_level"] == 'a':
  5449. tool_add_popup = FCInputDialog(title="New Tool ...",
  5450. text='Enter a Tool Diameter:',
  5451. min=0.0000, max=99.9999, decimals=4)
  5452. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5453. val, ok = tool_add_popup.get_value()
  5454. if ok:
  5455. if float(val) == 0:
  5456. self.inform.emit('[WARNING_NOTCL] %s' %
  5457. _("Please enter a tool diameter with non-zero value, in Float format."))
  5458. return
  5459. self.collection.get_active().on_tool_add(dia=float(val))
  5460. else:
  5461. self.inform.emit('[WARNING_NOTCL] %s...' %
  5462. _("Adding Tool cancelled"))
  5463. else:
  5464. msgbox = QtWidgets.QMessageBox()
  5465. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  5466. "Go to Preferences -> General - Show Advanced Options."))
  5467. msgbox.setWindowTitle("Tool adding ...")
  5468. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  5469. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5470. msgbox.setDefaultButton(bt_ok)
  5471. msgbox.exec_()
  5472. # work only if the notebook tab on focus is the Tools_Tab
  5473. if notebook_widget_name == 'tool_tab':
  5474. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5475. tool_add_popup = FCInputDialog(title="New Tool ...",
  5476. text='Enter a Tool Diameter:',
  5477. min=0.0000, max=99.9999, decimals=4)
  5478. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5479. val, ok = tool_add_popup.get_value()
  5480. # and only if the tool is NCC Tool
  5481. if tool_widget == self.ncclear_tool.toolName:
  5482. if ok:
  5483. if float(val) == 0:
  5484. self.inform.emit('[WARNING_NOTCL] %s' %
  5485. _("Please enter a tool diameter with non-zero value, in Float format."))
  5486. return
  5487. self.ncclear_tool.on_tool_add(dia=float(val))
  5488. else:
  5489. self.inform.emit('[WARNING_NOTCL] %s...' %
  5490. _("Adding Tool cancelled"))
  5491. # and only if the tool is Paint Area Tool
  5492. elif tool_widget == self.paint_tool.toolName:
  5493. if ok:
  5494. if float(val) == 0:
  5495. self.inform.emit('[WARNING_NOTCL] %s' %
  5496. _("Please enter a tool diameter with non-zero value, in Float format."))
  5497. return
  5498. self.paint_tool.on_tool_add(dia=float(val))
  5499. else:
  5500. self.inform.emit('[WARNING_NOTCL] %s...' %
  5501. _("Adding Tool cancelled"))
  5502. # and only if the tool is Solder Paste Dispensing Tool
  5503. elif tool_widget == self.paste_tool.toolName:
  5504. if ok:
  5505. if float(val) == 0:
  5506. self.inform.emit('[WARNING_NOTCL] %s' %
  5507. _("Please enter a tool diameter with non-zero value, in Float format."))
  5508. return
  5509. self.paste_tool.on_tool_add(dia=float(val))
  5510. else:
  5511. self.inform.emit('[WARNING_NOTCL] %s...' %
  5512. _("Adding Tool cancelled"))
  5513. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  5514. # See description bellow.
  5515. def on_delete_keypress(self):
  5516. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5517. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5518. if notebook_widget_name == 'selected_tab':
  5519. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5520. self.collection.get_active().on_tool_delete()
  5521. # work only if the notebook tab on focus is the Tools_Tab
  5522. elif notebook_widget_name == 'tool_tab':
  5523. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5524. # and only if the tool is NCC Tool
  5525. if tool_widget == self.ncclear_tool.toolName:
  5526. self.ncclear_tool.on_tool_delete()
  5527. # and only if the tool is Paint Tool
  5528. elif tool_widget == self.paint_tool.toolName:
  5529. self.paint_tool.on_tool_delete()
  5530. # and only if the tool is Solder Paste Dispensing Tool
  5531. elif tool_widget == self.paste_tool.toolName:
  5532. self.paste_tool.on_tool_delete()
  5533. else:
  5534. self.on_delete()
  5535. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  5536. # some screens you have to be careful where you hover with your mouse.
  5537. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  5538. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  5539. # Complicated, I know :)
  5540. def on_delete(self):
  5541. """
  5542. Delete the currently selected FlatCAMObjs.
  5543. :return: None
  5544. """
  5545. self.report_usage("on_delete()")
  5546. response = None
  5547. bt_ok = None
  5548. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  5549. # a geometry object before we update it.
  5550. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  5551. and self.grb_editor.editor_active is False:
  5552. if self.defaults["global_delete_confirmation"] is True:
  5553. msgbox = QtWidgets.QMessageBox()
  5554. msgbox.setWindowTitle(_("Delete objects"))
  5555. msgbox.setWindowIcon(QtGui.QIcon('share/deleteshape32.png'))
  5556. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  5557. msgbox.setText(_("Are you sure you want to permanently delete\n"
  5558. "the selected objects?"))
  5559. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5560. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5561. msgbox.setDefaultButton(bt_ok)
  5562. msgbox.exec_()
  5563. response = msgbox.clickedButton()
  5564. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  5565. if self.collection.get_active():
  5566. self.log.debug("App.on_delete()")
  5567. while self.collection.get_active():
  5568. obj_active = self.collection.get_active()
  5569. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  5570. if isinstance(obj_active, FlatCAMGerber):
  5571. for el in obj_active.mark_shapes:
  5572. obj_active.mark_shapes[el].clear(update=True)
  5573. obj_active.mark_shapes[el].enabled = False
  5574. # obj_active.mark_shapes[el] = None
  5575. del el
  5576. elif isinstance(obj_active, FlatCAMCNCjob):
  5577. try:
  5578. obj_active.annotation.clear(update=True)
  5579. obj_active.annotation.enabled = False
  5580. except AttributeError:
  5581. pass
  5582. self.delete_first_selected()
  5583. self.inform.emit('%s...' %
  5584. _("Object(s) deleted"))
  5585. # make sure that the selection shape is deleted, too
  5586. self.delete_selection_shape()
  5587. else:
  5588. self.inform.emit(_("Failed. No object(s) selected..."))
  5589. else:
  5590. self.inform.emit(_("Save the work in Editor and try again ..."))
  5591. def delete_first_selected(self):
  5592. # Keep this for later
  5593. try:
  5594. sel_obj = self.collection.get_active()
  5595. name = sel_obj.options["name"]
  5596. except AttributeError:
  5597. self.log.debug("Nothing selected for deletion")
  5598. return
  5599. # Remove from dictionary
  5600. self.collection.delete_active()
  5601. # Clear form
  5602. self.setup_component_editor()
  5603. self.inform.emit('%s: %s' %
  5604. (_("Object deleted"), name))
  5605. def on_set_origin(self):
  5606. """
  5607. Set the origin to the left mouse click position
  5608. :return: None
  5609. """
  5610. # display the message for the user
  5611. # and ask him to click on the desired position
  5612. self.report_usage("on_set_origin()")
  5613. def origin_replot():
  5614. def worker_task():
  5615. with self.proc_container.new('%s...' % _("Plotting")):
  5616. for obj in self.collection.get_list():
  5617. obj.plot()
  5618. self.plotcanvas.fit_view()
  5619. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  5620. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5621. self.inform.emit(_('Click to set the origin ...'))
  5622. self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  5623. # first disconnect it as it may have been used by something else
  5624. try:
  5625. self.replot_signal.disconnect()
  5626. except TypeError:
  5627. pass
  5628. self.replot_signal[list].connect(origin_replot)
  5629. def on_set_zero_click(self, event):
  5630. # this function will be available only for mouse left click
  5631. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5632. if event.button == 1:
  5633. if self.grid_status() == True:
  5634. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5635. else:
  5636. pos = pos_canvas
  5637. x = 0 - pos[0]
  5638. y = 0 - pos[1]
  5639. def worker_task():
  5640. with self.proc_container.new(_("Setting Origin...")):
  5641. for obj in self.collection.get_list():
  5642. obj.offset((x, y))
  5643. self.object_changed.emit(obj)
  5644. # Update the object bounding box options
  5645. a, b, c, d = obj.bounds()
  5646. obj.options['xmin'] = a
  5647. obj.options['ymin'] = b
  5648. obj.options['xmax'] = c
  5649. obj.options['ymax'] = d
  5650. self.inform.emit('[success]%s...' %
  5651. _('Origin set'))
  5652. self.replot_signal.emit([])
  5653. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5654. self.should_we_save = True
  5655. def on_jump_to(self, custom_location=None, fit_center=True):
  5656. """
  5657. Jump to a location by setting the mouse cursor location
  5658. :return:
  5659. """
  5660. self.report_usage("on_jump_to()")
  5661. if not custom_location:
  5662. dia_box = Dialog_box(title=_("Jump to ..."),
  5663. label=_("Enter the coordinates in format X,Y:"),
  5664. icon=QtGui.QIcon('share/jump_to16.png'))
  5665. if dia_box.ok is True:
  5666. try:
  5667. location = eval(dia_box.location)
  5668. if not isinstance(location, tuple):
  5669. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  5670. return
  5671. except:
  5672. return
  5673. else:
  5674. return
  5675. else:
  5676. location = custom_location
  5677. if fit_center:
  5678. self.plotcanvas.fit_center(loc=location)
  5679. cursor = QtGui.QCursor()
  5680. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5681. jump_loc = self.plotcanvas.translate_coords_2((location[0], location[1]))
  5682. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  5683. self.inform.emit('[success] %s' %
  5684. _("Done."))
  5685. return location
  5686. def on_copy_object(self):
  5687. self.report_usage("on_copy_object()")
  5688. def initialize(obj_init, app):
  5689. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5690. try:
  5691. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5692. except AttributeError:
  5693. pass
  5694. try:
  5695. obj_init.apertures = deepcopy(obj.apertures)
  5696. except AttributeError:
  5697. pass
  5698. try:
  5699. if obj.tools:
  5700. obj_init.tools = deepcopy(obj.tools)
  5701. except Exception as e:
  5702. log.debug("App.on_copy_object() --> %s" % str(e))
  5703. def initialize_excellon(obj_init, app):
  5704. obj_init.tools = deepcopy(obj.tools)
  5705. # drills are offset, so they need to be deep copied
  5706. obj_init.drills = deepcopy(obj.drills)
  5707. # slots are offset, so they need to be deep copied
  5708. obj_init.slots = deepcopy(obj.slots)
  5709. obj_init.create_geometry()
  5710. for obj in self.collection.get_selected():
  5711. obj_name = obj.options["name"]
  5712. try:
  5713. if isinstance(obj, FlatCAMExcellon):
  5714. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  5715. elif isinstance(obj, FlatCAMGerber):
  5716. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  5717. elif isinstance(obj, FlatCAMGeometry):
  5718. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  5719. except Exception as e:
  5720. return "Operation failed: %s" % str(e)
  5721. def on_copy_object2(self, custom_name):
  5722. def initialize_geometry(obj_init, app):
  5723. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5724. try:
  5725. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5726. except AttributeError:
  5727. pass
  5728. try:
  5729. obj_init.apertures = deepcopy(obj.apertures)
  5730. except AttributeError:
  5731. pass
  5732. try:
  5733. if obj.tools:
  5734. obj_init.tools = deepcopy(obj.tools)
  5735. except Exception as e:
  5736. log.debug("on_copy_object2() --> %s" % str(e))
  5737. def initialize_gerber(obj_init, app):
  5738. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5739. obj_init.apertures = deepcopy(obj.apertures)
  5740. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  5741. def initialize_excellon(obj_init, app):
  5742. obj_init.tools = deepcopy(obj.tools)
  5743. # drills are offset, so they need to be deep copied
  5744. obj_init.drills = deepcopy(obj.drills)
  5745. # slots are offset, so they need to be deep copied
  5746. obj_init.slots = deepcopy(obj.slots)
  5747. obj_init.create_geometry()
  5748. for obj in self.collection.get_selected():
  5749. obj_name = obj.options["name"]
  5750. try:
  5751. if isinstance(obj, FlatCAMExcellon):
  5752. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  5753. elif isinstance(obj, FlatCAMGerber):
  5754. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  5755. elif isinstance(obj, FlatCAMGeometry):
  5756. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  5757. except Exception as e:
  5758. return "Operation failed: %s" % str(e)
  5759. def on_rename_object(self, text):
  5760. self.report_usage("on_rename_object()")
  5761. named_obj = self.collection.get_active()
  5762. for obj in named_obj:
  5763. if obj is list:
  5764. self.on_rename_object(text)
  5765. else:
  5766. try:
  5767. obj.options['name'] = text
  5768. except Exception as e:
  5769. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  5770. def convert_any2geo(self):
  5771. self.report_usage("convert_any2geo()")
  5772. def initialize(obj_init, app):
  5773. obj_init.solid_geometry = obj.solid_geometry
  5774. try:
  5775. obj_init.follow_geometry = obj.follow_geometry
  5776. except AttributeError:
  5777. pass
  5778. try:
  5779. obj_init.apertures = obj.apertures
  5780. except AttributeError:
  5781. pass
  5782. try:
  5783. if obj.tools:
  5784. obj_init.tools = obj.tools
  5785. except AttributeError:
  5786. pass
  5787. def initialize_excellon(obj_init, app):
  5788. # objs = self.collection.get_selected()
  5789. # FlatCAMGeometry.merge(objs, obj)
  5790. solid_geo = []
  5791. for tool in obj.tools:
  5792. for geo in obj.tools[tool]['solid_geometry']:
  5793. solid_geo.append(geo)
  5794. obj_init.solid_geometry = deepcopy(solid_geo)
  5795. if not self.collection.get_selected():
  5796. log.warning("App.convert_any2geo --> No object selected")
  5797. self.inform.emit('[WARNING_NOTCL] %s' %
  5798. _("No object is selected. Select an object and try again."))
  5799. return
  5800. for obj in self.collection.get_selected():
  5801. obj_name = obj.options["name"]
  5802. try:
  5803. if isinstance(obj, FlatCAMExcellon):
  5804. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  5805. else:
  5806. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  5807. except Exception as e:
  5808. return "Operation failed: %s" % str(e)
  5809. def convert_any2gerber(self):
  5810. self.report_usage("convert_any2gerber()")
  5811. def initialize_geometry(obj_init, app):
  5812. apertures = {}
  5813. apid = 0
  5814. apertures[str(apid)] = {}
  5815. apertures[str(apid)]['geometry'] = []
  5816. for obj_orig in obj.solid_geometry:
  5817. new_elem = dict()
  5818. new_elem['solid'] = obj_orig
  5819. new_elem['follow'] = obj_orig.exterior
  5820. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  5821. apertures[str(apid)]['size'] = 0.0
  5822. apertures[str(apid)]['type'] = 'C'
  5823. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5824. obj_init.apertures = deepcopy(apertures)
  5825. def initialize_excellon(obj_init, app):
  5826. apertures = {}
  5827. apid = 10
  5828. for tool in obj.tools:
  5829. apertures[str(apid)] = {}
  5830. apertures[str(apid)]['geometry'] = []
  5831. for geo in obj.tools[tool]['solid_geometry']:
  5832. new_el = dict()
  5833. new_el['solid'] = geo
  5834. new_el['follow'] = geo.exterior
  5835. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  5836. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  5837. apertures[str(apid)]['type'] = 'C'
  5838. apid += 1
  5839. # create solid_geometry
  5840. solid_geometry = []
  5841. for apid in apertures:
  5842. for geo_el in apertures[apid]['geometry']:
  5843. solid_geometry.append(geo_el['solid'])
  5844. solid_geometry = MultiPolygon(solid_geometry)
  5845. solid_geometry = solid_geometry.buffer(0.0000001)
  5846. obj_init.solid_geometry = deepcopy(solid_geometry)
  5847. obj_init.apertures = deepcopy(apertures)
  5848. # clear the working objects (perhaps not necessary due of Python GC)
  5849. apertures.clear()
  5850. if not self.collection.get_selected():
  5851. log.warning("App.convert_any2gerber --> No object selected")
  5852. self.inform.emit('[WARNING_NOTCL] %s' %
  5853. _("No object is selected. Select an object and try again."))
  5854. return
  5855. for obj in self.collection.get_selected():
  5856. obj_name = obj.options["name"]
  5857. try:
  5858. if isinstance(obj, FlatCAMExcellon):
  5859. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  5860. elif isinstance(obj, FlatCAMGeometry):
  5861. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  5862. else:
  5863. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  5864. except Exception as e:
  5865. return "Operation failed: %s" % str(e)
  5866. def abort_all_tasks(self):
  5867. if self.abort_flag is False:
  5868. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  5869. self.abort_flag = True
  5870. def app_is_idle(self):
  5871. if self.abort_flag:
  5872. self.inform.emit('[WARNING_NOTCL] %s' %
  5873. _("The current task was gracefully closed on user request..."))
  5874. self.abort_flag = False
  5875. def on_selectall(self):
  5876. self.report_usage("on_selectall()")
  5877. # delete the possible selection box around a possible selected object
  5878. self.delete_selection_shape()
  5879. for name in self.collection.get_names():
  5880. self.collection.set_active(name)
  5881. curr_sel_obj = self.collection.get_by_name(name)
  5882. # create the selection box around the selected object
  5883. if self.defaults['global_selection_shape'] is True:
  5884. self.draw_selection_shape(curr_sel_obj)
  5885. def on_preferences(self):
  5886. # add the tab if it was closed
  5887. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  5888. # delete the absolute and relative position and messages in the infobar
  5889. self.ui.position_label.setText("")
  5890. self.ui.rel_position_label.setText("")
  5891. # Switch plot_area to preferences page
  5892. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  5893. # self.ui.show()
  5894. # this disconnect() is done so the slot will be connected only once
  5895. try:
  5896. self.ui.plot_tab_area.tab_closed_signal.disconnect(self.on_preferences_closed)
  5897. except (TypeError, AttributeError):
  5898. pass
  5899. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_preferences_closed)
  5900. # detect changes in the preferences
  5901. for idx in range(self.ui.pref_tab_area.count()):
  5902. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  5903. try:
  5904. try:
  5905. tb.textEdited.disconnect(self.on_preferences_edited)
  5906. except (TypeError, AttributeError):
  5907. pass
  5908. tb.textEdited.connect(self.on_preferences_edited)
  5909. except AttributeError:
  5910. pass
  5911. try:
  5912. try:
  5913. tb.modificationChanged.disconnect(self.on_preferences_edited)
  5914. except (TypeError, AttributeError):
  5915. pass
  5916. tb.modificationChanged.connect(self.on_preferences_edited)
  5917. except AttributeError:
  5918. pass
  5919. try:
  5920. try:
  5921. tb.toggled.disconnect(self.on_preferences_edited)
  5922. except (TypeError, AttributeError):
  5923. pass
  5924. tb.toggled.connect(self.on_preferences_edited)
  5925. except AttributeError:
  5926. pass
  5927. try:
  5928. try:
  5929. tb.valueChanged.disconnect(self.on_preferences_edited)
  5930. except (TypeError, AttributeError):
  5931. pass
  5932. tb.valueChanged.connect(self.on_preferences_edited)
  5933. except AttributeError:
  5934. pass
  5935. try:
  5936. try:
  5937. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  5938. except (TypeError, AttributeError):
  5939. pass
  5940. tb.currentIndexChanged.connect(self.on_preferences_edited)
  5941. except AttributeError:
  5942. pass
  5943. def on_preferences_edited(self):
  5944. self.inform.emit('[WARNING_NOTCL] %s' %
  5945. _("Preferences edited but not saved."))
  5946. self.preferences_changed_flag = True
  5947. def on_preferences_closed(self):
  5948. # disconnect
  5949. for idx in range(self.ui.pref_tab_area.count()):
  5950. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  5951. try:
  5952. tb.textEdited.disconnect(self.on_preferences_edited)
  5953. except (TypeError, AttributeError):
  5954. pass
  5955. try:
  5956. tb.modificationChanged.disconnect(self.on_preferences_edited)
  5957. except (TypeError, AttributeError):
  5958. pass
  5959. try:
  5960. tb.toggled.disconnect(self.on_preferences_edited)
  5961. except (TypeError, AttributeError):
  5962. pass
  5963. try:
  5964. tb.valueChanged.disconnect(self.on_preferences_edited)
  5965. except (TypeError, AttributeError):
  5966. pass
  5967. try:
  5968. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  5969. except (TypeError, AttributeError):
  5970. pass
  5971. if self.preferences_changed_flag is True:
  5972. msgbox = QtWidgets.QMessageBox()
  5973. msgbox.setText(_("One or more values are changed.\n"
  5974. "Do you want to save the Preferences?"))
  5975. msgbox.setWindowTitle(_("Save Preferences"))
  5976. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  5977. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5978. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5979. msgbox.setDefaultButton(bt_yes)
  5980. msgbox.exec_()
  5981. response = msgbox.clickedButton()
  5982. if response == bt_yes:
  5983. self.on_save_button()
  5984. self.inform.emit('[success] %s' %
  5985. _("Preferences saved."))
  5986. else:
  5987. self.preferences_changed_flag = False
  5988. return
  5989. def on_flipy(self):
  5990. self.report_usage("on_flipy()")
  5991. obj_list = self.collection.get_selected()
  5992. xminlist = []
  5993. yminlist = []
  5994. xmaxlist = []
  5995. ymaxlist = []
  5996. if not obj_list:
  5997. self.inform.emit('[WARNING_NOTCL] %s' %
  5998. _("No object selected to Flip on Y axis."))
  5999. else:
  6000. try:
  6001. # first get a bounding box to fit all
  6002. for obj in obj_list:
  6003. xmin, ymin, xmax, ymax = obj.bounds()
  6004. xminlist.append(xmin)
  6005. yminlist.append(ymin)
  6006. xmaxlist.append(xmax)
  6007. ymaxlist.append(ymax)
  6008. # get the minimum x,y and maximum x,y for all objects selected
  6009. xminimal = min(xminlist)
  6010. yminimal = min(yminlist)
  6011. xmaximal = max(xmaxlist)
  6012. ymaximal = max(ymaxlist)
  6013. px = 0.5 * (xminimal + xmaximal)
  6014. py = 0.5 * (yminimal + ymaximal)
  6015. # execute mirroring
  6016. for obj in obj_list:
  6017. obj.mirror('X', [px, py])
  6018. obj.plot()
  6019. self.object_changed.emit(obj)
  6020. self.inform.emit('[success] %s' %
  6021. _("Flip on Y axis done."))
  6022. except Exception as e:
  6023. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6024. (_("Flip action was not executed."), str(e)))
  6025. return
  6026. def on_flipx(self):
  6027. self.report_usage("on_flipx()")
  6028. obj_list = self.collection.get_selected()
  6029. xminlist = []
  6030. yminlist = []
  6031. xmaxlist = []
  6032. ymaxlist = []
  6033. if not obj_list:
  6034. self.inform.emit('[WARNING_NOTCL] %s' %
  6035. _("No object selected to Flip on X axis."))
  6036. else:
  6037. try:
  6038. # first get a bounding box to fit all
  6039. for obj in obj_list:
  6040. xmin, ymin, xmax, ymax = obj.bounds()
  6041. xminlist.append(xmin)
  6042. yminlist.append(ymin)
  6043. xmaxlist.append(xmax)
  6044. ymaxlist.append(ymax)
  6045. # get the minimum x,y and maximum x,y for all objects selected
  6046. xminimal = min(xminlist)
  6047. yminimal = min(yminlist)
  6048. xmaximal = max(xmaxlist)
  6049. ymaximal = max(ymaxlist)
  6050. px = 0.5 * (xminimal + xmaximal)
  6051. py = 0.5 * (yminimal + ymaximal)
  6052. # execute mirroring
  6053. for obj in obj_list:
  6054. obj.mirror('Y', [px, py])
  6055. obj.plot()
  6056. self.object_changed.emit(obj)
  6057. self.inform.emit('[success] %s' %
  6058. _("Flip on X axis done."))
  6059. except Exception as e:
  6060. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6061. (_("Flip action was not executed."), str(e)))
  6062. return
  6063. def on_rotate(self, silent=False, preset=None):
  6064. self.report_usage("on_rotate()")
  6065. obj_list = self.collection.get_selected()
  6066. xminlist = []
  6067. yminlist = []
  6068. xmaxlist = []
  6069. ymaxlist = []
  6070. if not obj_list:
  6071. self.inform.emit('[WARNING_NOTCL] %s' %
  6072. _("No object selected to Rotate."))
  6073. else:
  6074. if silent is False:
  6075. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6076. min=-360, max=360, decimals=4,
  6077. init_val=float(self.defaults['tools_transform_rotate']))
  6078. num, ok = rotatebox.get_value()
  6079. else:
  6080. num = preset
  6081. ok = True
  6082. if ok:
  6083. try:
  6084. # first get a bounding box to fit all
  6085. for obj in obj_list:
  6086. xmin, ymin, xmax, ymax = obj.bounds()
  6087. xminlist.append(xmin)
  6088. yminlist.append(ymin)
  6089. xmaxlist.append(xmax)
  6090. ymaxlist.append(ymax)
  6091. # get the minimum x,y and maximum x,y for all objects selected
  6092. xminimal = min(xminlist)
  6093. yminimal = min(yminlist)
  6094. xmaximal = max(xmaxlist)
  6095. ymaximal = max(ymaxlist)
  6096. px = 0.5 * (xminimal + xmaximal)
  6097. py = 0.5 * (yminimal + ymaximal)
  6098. for sel_obj in obj_list:
  6099. sel_obj.rotate(-float(num), point=(px, py))
  6100. sel_obj.plot()
  6101. self.object_changed.emit(sel_obj)
  6102. self.inform.emit('[success] %s' %
  6103. _("Rotation done."))
  6104. except Exception as e:
  6105. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6106. (_("Rotation movement was not executed."), str(e)))
  6107. return
  6108. def on_skewx(self):
  6109. self.report_usage("on_skewx()")
  6110. obj_list = self.collection.get_selected()
  6111. xminlist = []
  6112. yminlist = []
  6113. if not obj_list:
  6114. self.inform.emit('[WARNING_NOTCL] %s' %
  6115. _("No object selected to Skew/Shear on X axis."))
  6116. else:
  6117. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6118. min=-360, max=360, decimals=4,
  6119. init_val=float(self.defaults['tools_transform_skew_x']))
  6120. num, ok = skewxbox.get_value()
  6121. if ok:
  6122. # first get a bounding box to fit all
  6123. for obj in obj_list:
  6124. xmin, ymin, xmax, ymax = obj.bounds()
  6125. xminlist.append(xmin)
  6126. yminlist.append(ymin)
  6127. # get the minimum x,y and maximum x,y for all objects selected
  6128. xminimal = min(xminlist)
  6129. yminimal = min(yminlist)
  6130. for obj in obj_list:
  6131. obj.skew(num, 0, point=(xminimal, yminimal))
  6132. obj.plot()
  6133. self.object_changed.emit(obj)
  6134. self.inform.emit('[success] %s' %
  6135. _("Skew on X axis done."))
  6136. def on_skewy(self):
  6137. self.report_usage("on_skewy()")
  6138. obj_list = self.collection.get_selected()
  6139. xminlist = []
  6140. yminlist = []
  6141. if not obj_list:
  6142. self.inform.emit('[WARNING_NOTCL] %s' %
  6143. _("No object selected to Skew/Shear on Y axis."))
  6144. else:
  6145. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6146. min=-360, max=360, decimals=4,
  6147. init_val=float(self.defaults['tools_transform_skew_y']))
  6148. num, ok = skewybox.get_value()
  6149. if ok:
  6150. # first get a bounding box to fit all
  6151. for obj in obj_list:
  6152. xmin, ymin, xmax, ymax = obj.bounds()
  6153. xminlist.append(xmin)
  6154. yminlist.append(ymin)
  6155. # get the minimum x,y and maximum x,y for all objects selected
  6156. xminimal = min(xminlist)
  6157. yminimal = min(yminlist)
  6158. for obj in obj_list:
  6159. obj.skew(0, num, point=(xminimal, yminimal))
  6160. obj.plot()
  6161. self.object_changed.emit(obj)
  6162. self.inform.emit('[success] %s' %
  6163. _("Skew on Y axis done."))
  6164. def on_plots_updated(self):
  6165. """
  6166. Callback used to report when the plots have changed.
  6167. Adjust axes and zooms to fit.
  6168. :return: None
  6169. """
  6170. self.plotcanvas.update() # TODO: Need update canvas?
  6171. self.on_zoom_fit(None)
  6172. self.collection.update_view()
  6173. # self.inform.emit(_("Plots updated ..."))
  6174. # TODO: Rework toolbar 'clear', 'replot' functions
  6175. def on_toolbar_replot(self):
  6176. """
  6177. Callback for toolbar button. Re-plots all objects.
  6178. :return: None
  6179. """
  6180. self.report_usage("on_toolbar_replot")
  6181. self.log.debug("on_toolbar_replot()")
  6182. try:
  6183. self.collection.get_active().read_form()
  6184. except AttributeError:
  6185. self.log.debug("on_toolbar_replot(): AttributeError")
  6186. pass
  6187. self.plot_all()
  6188. def on_row_activated(self, index):
  6189. if index.isValid():
  6190. if index.internalPointer().parent_item != self.collection.root_item:
  6191. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6192. self.collection.on_item_activated(index)
  6193. def grid_status(self):
  6194. if self.ui.grid_snap_btn.isChecked():
  6195. return True
  6196. else:
  6197. return False
  6198. def populate_cmenu_grids(self):
  6199. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6200. self.ui.cmenu_gridmenu.clear()
  6201. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  6202. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  6203. grid_toggle.setCheckable(True)
  6204. if self.grid_status() == True:
  6205. grid_toggle.setChecked(True)
  6206. else:
  6207. grid_toggle.setChecked(False)
  6208. self.ui.cmenu_gridmenu.addSeparator()
  6209. for grid in sorted_list:
  6210. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  6211. action.triggered.connect(self.set_grid)
  6212. self.ui.cmenu_gridmenu.addSeparator()
  6213. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  6214. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  6215. grid_add.triggered.connect(self.on_grid_add)
  6216. grid_delete.triggered.connect(self.on_grid_delete)
  6217. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  6218. def set_grid(self):
  6219. self.ui.grid_gap_x_entry.setText(self.sender().text())
  6220. self.ui.grid_gap_y_entry.setText(self.sender().text())
  6221. def on_grid_add(self):
  6222. # ## Current application units in lower Case
  6223. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6224. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  6225. text=_('Enter a Grid Value:'),
  6226. min=0.0000, max=99.9999, decimals=4)
  6227. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  6228. val, ok = grid_add_popup.get_value()
  6229. if ok:
  6230. if float(val) == 0:
  6231. self.inform.emit('[WARNING_NOTCL] %s' %
  6232. _("Please enter a grid value with non-zero value, in Float format."))
  6233. return
  6234. else:
  6235. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  6236. self.defaults["global_grid_context_menu"][str(units)].append(val)
  6237. self.inform.emit('[success] %s...' %
  6238. _("New Grid added"))
  6239. else:
  6240. self.inform.emit('[WARNING_NOTCL] %s...' %
  6241. _("Grid already exists"))
  6242. else:
  6243. self.inform.emit('[WARNING_NOTCL] %s...' %
  6244. _("Adding New Grid cancelled"))
  6245. def on_grid_delete(self):
  6246. # ## Current application units in lower Case
  6247. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6248. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  6249. text='Enter a Grid Value:',
  6250. min=0.0000, max=99.9999, decimals=4)
  6251. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  6252. val, ok = grid_del_popup.get_value()
  6253. if ok:
  6254. if float(val) == 0:
  6255. self.inform.emit('[WARNING_NOTCL] %s' %
  6256. _("Please enter a grid value with non-zero value, in Float format."))
  6257. return
  6258. else:
  6259. try:
  6260. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  6261. except ValueError:
  6262. self.inform.emit('[ERROR_NOTCL]%s...' %
  6263. _(" Grid Value does not exist"))
  6264. return
  6265. self.inform.emit('[success] %s...' %
  6266. _("Grid Value deleted"))
  6267. else:
  6268. self.inform.emit('[WARNING_NOTCL] %s...' %
  6269. _("Delete Grid value cancelled"))
  6270. def on_shortcut_list(self):
  6271. self.report_usage("on_shortcut_list()")
  6272. # add the tab if it was closed
  6273. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  6274. # delete the absolute and relative position and messages in the infobar
  6275. self.ui.position_label.setText("")
  6276. self.ui.rel_position_label.setText("")
  6277. # Switch plot_area to preferences page
  6278. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  6279. # self.ui.show()
  6280. def on_select_tab(self, name):
  6281. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  6282. if self.ui.splitter.sizes()[0] == 0:
  6283. self.ui.splitter.setSizes([1, 1])
  6284. else:
  6285. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  6286. self.ui.splitter.setSizes([0, 1])
  6287. if name == 'project':
  6288. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6289. elif name == 'selected':
  6290. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6291. elif name == 'tool':
  6292. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  6293. def on_copy_name(self):
  6294. self.report_usage("on_copy_name()")
  6295. obj = self.collection.get_active()
  6296. try:
  6297. name = obj.options["name"]
  6298. except AttributeError:
  6299. log.debug("on_copy_name() --> No object selected to copy it's name")
  6300. self.inform.emit('[WARNING_NOTCL]%s' %
  6301. _(" No object selected to copy it's name"))
  6302. return
  6303. self.clipboard.setText(name)
  6304. self.inform.emit(_("Name copied on clipboard ..."))
  6305. def on_mouse_click_over_plot(self, event):
  6306. """
  6307. Default actions are:
  6308. :param event: Contains information about the event, like which button
  6309. was clicked, the pixel coordinates and the axes coordinates.
  6310. :return: None
  6311. """
  6312. self.pos = []
  6313. if self.is_legacy is False:
  6314. event_pos = event.pos
  6315. if self.defaults["global_pan_button"] == '2':
  6316. pan_button = 2
  6317. else:
  6318. pan_button = 3
  6319. # Set the mouse button for panning
  6320. self.plotcanvas.view.camera.pan_button_setting = pan_button
  6321. else:
  6322. event_pos = (event.xdata, event.ydata)
  6323. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6324. if self.defaults["global_pan_button"] == '2':
  6325. pan_button = 3
  6326. else:
  6327. pan_button = 2
  6328. # So it can receive key presses
  6329. self.plotcanvas.native.setFocus()
  6330. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6331. if self.grid_status() == True:
  6332. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  6333. else:
  6334. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  6335. try:
  6336. modifiers = QtWidgets.QApplication.keyboardModifiers()
  6337. if event.button == 1:
  6338. # Reset here the relative coordinates so there is a new reference on the click position
  6339. if self.rel_point1 is None:
  6340. self.rel_point1 = self.pos
  6341. else:
  6342. self.rel_point2 = copy(self.rel_point1)
  6343. self.rel_point1 = self.pos
  6344. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  6345. if modifiers == QtCore.Qt.ShiftModifier:
  6346. # do not auto open the Project Tab
  6347. self.click_noproject = True
  6348. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  6349. self.inform.emit('[success] %s' %
  6350. _("Coordinates copied to clipboard."))
  6351. return
  6352. self.on_mouse_move_over_plot(event, origin_click=True)
  6353. except Exception as e:
  6354. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  6355. def on_double_click_over_plot(self, event):
  6356. if event.button == 1:
  6357. self.doubleclick = True
  6358. def on_mouse_move_over_plot(self, event, origin_click=None):
  6359. """
  6360. Callback for the mouse motion event over the plot.
  6361. :param event: Contains information about the event.
  6362. :param origin_click
  6363. :return: None
  6364. """
  6365. if self.is_legacy is False:
  6366. event_pos = event.pos
  6367. if self.defaults["global_pan_button"] == '2':
  6368. pan_button = 2
  6369. else:
  6370. pan_button = 3
  6371. event_is_dragging = event.is_dragging
  6372. else:
  6373. event_pos = (event.xdata, event.ydata)
  6374. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6375. if self.defaults["global_pan_button"] == '2':
  6376. pan_button = 3
  6377. else:
  6378. pan_button = 2
  6379. event_is_dragging = self.plotcanvas.is_dragging
  6380. # So it can receive key presses
  6381. self.plotcanvas.native.setFocus()
  6382. self.pos_jump = event_pos
  6383. self.ui.popMenu.mouse_is_panning = False
  6384. if not origin_click:
  6385. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  6386. if event.button == pan_button and event_is_dragging == 1:
  6387. self.ui.popMenu.mouse_is_panning = True
  6388. return
  6389. if self.rel_point1 is not None:
  6390. try: # May fail in case mouse not within axes
  6391. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6392. if self.grid_status() == True:
  6393. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6394. if self.is_legacy is False:
  6395. # Update cursor
  6396. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  6397. symbol='++', edge_color='black', size=20)
  6398. else:
  6399. self.app_cursor.set_data(event, (pos[0], pos[1]))
  6400. else:
  6401. pos = (pos_canvas[0], pos_canvas[1])
  6402. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  6403. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  6404. dx = pos[0] - self.rel_point1[0]
  6405. dy = pos[1] - self.rel_point1[1]
  6406. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  6407. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  6408. self.mouse = [pos[0], pos[1]]
  6409. # if the mouse is moved and the LMB is clicked then the action is a selection
  6410. if event_is_dragging == 1 and event.button == 1:
  6411. self.delete_selection_shape()
  6412. if dx < 0:
  6413. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  6414. face_color=self.defaults['global_alt_sel_fill'])
  6415. self.selection_type = False
  6416. else:
  6417. self.draw_moving_selection_shape(self.pos, pos)
  6418. self.selection_type = True
  6419. # hover effect - enabled in Preferences -> General -> GUI Settings
  6420. if self.defaults['global_hover']:
  6421. for obj in self.collection.get_list():
  6422. try:
  6423. # select the object(s) only if it is enabled (plotted)
  6424. if obj.options['plot']:
  6425. if obj not in self.collection.get_selected():
  6426. poly_obj = Polygon(
  6427. [(obj.options['xmin'], obj.options['ymin']),
  6428. (obj.options['xmax'], obj.options['ymin']),
  6429. (obj.options['xmax'], obj.options['ymax']),
  6430. (obj.options['xmin'], obj.options['ymax'])]
  6431. )
  6432. if Point(pos).within(poly_obj):
  6433. if obj.isHovering is False:
  6434. obj.isHovering = True
  6435. obj.notHovering = True
  6436. # create the selection box around the selected object
  6437. self.draw_hover_shape(obj, color='#d1e0e0')
  6438. else:
  6439. if obj.notHovering is True:
  6440. obj.notHovering = False
  6441. obj.isHovering = False
  6442. self.delete_hover_shape()
  6443. except:
  6444. # the Exception here will happen if we try to select on screen and we have an
  6445. # newly (and empty) just created Geometry or Excellon object that do not have the
  6446. # xmin, xmax, ymin, ymax options.
  6447. # In this case poly_obj creation (see above) will fail
  6448. pass
  6449. except:
  6450. self.ui.position_label.setText("")
  6451. self.ui.rel_position_label.setText("")
  6452. self.mouse = None
  6453. def on_mouse_click_release_over_plot(self, event):
  6454. """
  6455. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  6456. and has been registered in ''self.__init__()''.
  6457. :param event: contains information about the event.
  6458. :return:
  6459. """
  6460. pos = 0, 0
  6461. if self.is_legacy is False:
  6462. event_pos = event.pos
  6463. right_button = 2
  6464. else:
  6465. event_pos = (event.xdata, event.ydata)
  6466. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6467. right_button = 3
  6468. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6469. if self.grid_status() == True:
  6470. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6471. else:
  6472. pos = (pos_canvas[0], pos_canvas[1])
  6473. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  6474. # canvas menu
  6475. if event.button == right_button: # right click
  6476. if self.ui.popMenu.mouse_is_panning is False:
  6477. self.cursor = QtGui.QCursor()
  6478. self.populate_cmenu_grids()
  6479. self.ui.popMenu.popup(self.cursor.pos())
  6480. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  6481. # selection and then select a type of selection ("enclosing" or "touching")
  6482. try:
  6483. if event.button == 1: # left click
  6484. if self.doubleclick is True:
  6485. self.doubleclick = False
  6486. if self.collection.get_selected():
  6487. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6488. if self.ui.splitter.sizes()[0] == 0:
  6489. self.ui.splitter.setSizes([1, 1])
  6490. # delete the selection shape(S) as it may be in the way
  6491. self.delete_selection_shape()
  6492. self.delete_hover_shape()
  6493. else:
  6494. if self.selection_type is not None:
  6495. self.selection_area_handler(self.pos, pos, self.selection_type)
  6496. self.selection_type = None
  6497. else:
  6498. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  6499. if key_modifier == QtCore.Qt.ShiftModifier:
  6500. mod_key = 'Shift'
  6501. elif key_modifier == QtCore.Qt.ControlModifier:
  6502. mod_key = 'Control'
  6503. else:
  6504. mod_key = None
  6505. if mod_key == self.defaults["global_mselect_key"]:
  6506. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  6507. # deselect, and if it's not selected then it will be selected
  6508. # If there is no active command (self.command_active is None) then we check if we clicked
  6509. # on a object by checking the bounding limits against mouse click position
  6510. if self.command_active is None:
  6511. self.select_objects(key='CTRL')
  6512. self.delete_hover_shape()
  6513. else:
  6514. # If there is no active command (self.command_active is None) then we check if we clicked
  6515. # on a object by checking the bounding limits against mouse click position
  6516. if self.command_active is None:
  6517. self.select_objects()
  6518. self.delete_hover_shape()
  6519. except Exception as e:
  6520. log.warning("Error: %s" % str(e))
  6521. return
  6522. def selection_area_handler(self, start_pos, end_pos, sel_type):
  6523. """
  6524. :param start_pos: mouse position when the selection LMB click was done
  6525. :param end_pos: mouse position when the left mouse button is released
  6526. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  6527. :return:
  6528. """
  6529. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  6530. self.delete_selection_shape()
  6531. for obj in self.collection.get_list():
  6532. try:
  6533. # select the object(s) only if it is enabled (plotted)
  6534. if obj.options['plot']:
  6535. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  6536. (obj.options['xmax'], obj.options['ymin']),
  6537. (obj.options['xmax'], obj.options['ymax']),
  6538. (obj.options['xmin'], obj.options['ymax'])])
  6539. if sel_type is True:
  6540. if poly_obj.within(poly_selection):
  6541. # create the selection box around the selected object
  6542. if self.defaults['global_selection_shape'] is True:
  6543. self.draw_selection_shape(obj)
  6544. self.collection.set_active(obj.options['name'])
  6545. else:
  6546. if poly_selection.intersects(poly_obj):
  6547. # create the selection box around the selected object
  6548. if self.defaults['global_selection_shape'] is True:
  6549. self.draw_selection_shape(obj)
  6550. self.collection.set_active(obj.options['name'])
  6551. except Exception as e:
  6552. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  6553. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  6554. # In this case poly_obj creation (see above) will fail
  6555. log.debug("App.selection_area_handler() --> %s" % str(e))
  6556. def select_objects(self, key=None):
  6557. # list where we store the overlapped objects under our mouse left click position
  6558. objects_under_the_click_list = []
  6559. # Populate the list with the overlapped objects on the click position
  6560. curr_x, curr_y = self.pos
  6561. for obj in self.all_objects_list:
  6562. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  6563. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  6564. if obj.options['name'] not in objects_under_the_click_list:
  6565. if obj.options['plot']:
  6566. # add objects to the objects_under_the_click list only if the object is plotted
  6567. # (active and not disabled)
  6568. objects_under_the_click_list.append(obj.options['name'])
  6569. try:
  6570. # If there is no element in the overlapped objects list then make everyone inactive
  6571. # because we selected "nothing"
  6572. if not objects_under_the_click_list:
  6573. self.collection.set_all_inactive()
  6574. # delete the possible selection box around a possible selected object
  6575. self.delete_selection_shape()
  6576. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  6577. # only when working on App
  6578. if self.call_source == 'app':
  6579. if self.click_noproject is False:
  6580. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6581. else:
  6582. # restore auto open the Project Tab
  6583. self.click_noproject = False
  6584. # delete any text in the status bar, implicitly the last object name that was selected
  6585. self.inform.emit("")
  6586. else:
  6587. self.call_source = 'app'
  6588. else:
  6589. # case when there is only an object under the click and we toggle it
  6590. if len(objects_under_the_click_list) == 1:
  6591. if self.collection.get_active() is None:
  6592. self.collection.set_active(objects_under_the_click_list[0])
  6593. # create the selection box around the selected object
  6594. curr_sel_obj = self.collection.get_active()
  6595. if self.defaults['global_selection_shape'] is True:
  6596. self.draw_selection_shape(curr_sel_obj)
  6597. # self.inform.emit('[selected] %s: %s selected' %
  6598. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6599. if curr_sel_obj.kind == 'gerber':
  6600. self.inform.emit(
  6601. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6602. color='green', name=str(curr_sel_obj.options['name'])))
  6603. elif curr_sel_obj.kind == 'excellon':
  6604. self.inform.emit(
  6605. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6606. color='brown', name=str(curr_sel_obj.options['name'])))
  6607. elif curr_sel_obj.kind == 'cncjob':
  6608. self.inform.emit(
  6609. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6610. color='blue', name=str(curr_sel_obj.options['name'])))
  6611. elif curr_sel_obj.kind == 'geometry':
  6612. self.inform.emit(
  6613. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6614. color='red', name=str(curr_sel_obj.options['name'])))
  6615. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  6616. self.collection.set_all_inactive()
  6617. self.delete_selection_shape()
  6618. self.collection.set_active(objects_under_the_click_list[0])
  6619. # create the selection box around the selected object
  6620. curr_sel_obj = self.collection.get_active()
  6621. if self.defaults['global_selection_shape'] is True:
  6622. self.draw_selection_shape(curr_sel_obj)
  6623. # self.inform.emit('[selected] %s: %s selected' %
  6624. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6625. if curr_sel_obj.kind == 'gerber':
  6626. self.inform.emit(
  6627. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6628. color='green', name=str(curr_sel_obj.options['name'])))
  6629. elif curr_sel_obj.kind == 'excellon':
  6630. self.inform.emit(
  6631. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6632. color='brown', name=str(curr_sel_obj.options['name'])))
  6633. elif curr_sel_obj.kind == 'cncjob':
  6634. self.inform.emit(
  6635. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6636. color='blue', name=str(curr_sel_obj.options['name'])))
  6637. elif curr_sel_obj.kind == 'geometry':
  6638. self.inform.emit(
  6639. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6640. color='red', name=str(curr_sel_obj.options['name'])))
  6641. else:
  6642. self.collection.set_all_inactive()
  6643. self.delete_selection_shape()
  6644. if self.call_source == 'app':
  6645. # delete any text in the status bar, implicitly the last object name that was selected
  6646. self.inform.emit("")
  6647. else:
  6648. self.call_source = 'app'
  6649. else:
  6650. # If there is no selected object
  6651. # make active the first element of the overlapped objects list
  6652. if self.collection.get_active() is None:
  6653. self.collection.set_active(objects_under_the_click_list[0])
  6654. name_sel_obj = self.collection.get_active().options['name']
  6655. # In case that there is a selected object but it is not in the overlapped object list
  6656. # make that object inactive and activate the first element in the overlapped object list
  6657. if name_sel_obj not in objects_under_the_click_list:
  6658. self.collection.set_inactive(name_sel_obj)
  6659. name_sel_obj = objects_under_the_click_list[0]
  6660. self.collection.set_active(name_sel_obj)
  6661. else:
  6662. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  6663. self.collection.set_all_inactive()
  6664. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  6665. len(objects_under_the_click_list)])
  6666. curr_sel_obj = self.collection.get_active()
  6667. # delete the possible selection box around a possible selected object
  6668. self.delete_selection_shape()
  6669. # create the selection box around the selected object
  6670. if self.defaults['global_selection_shape'] is True:
  6671. self.draw_selection_shape(curr_sel_obj)
  6672. # self.inform.emit('[selected] %s: %s selected' %
  6673. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6674. if curr_sel_obj.kind == 'gerber':
  6675. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6676. color='green', name=str(curr_sel_obj.options['name'])))
  6677. elif curr_sel_obj.kind == 'excellon':
  6678. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6679. color='brown', name=str(curr_sel_obj.options['name'])))
  6680. elif curr_sel_obj.kind == 'cncjob':
  6681. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6682. color='blue', name=str(curr_sel_obj.options['name'])))
  6683. elif curr_sel_obj.kind == 'geometry':
  6684. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6685. color='red', name=str(curr_sel_obj.options['name'])))
  6686. # for obj in self.collection.get_list():
  6687. # obj.plot()
  6688. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  6689. # TODO: on selected objects change the object colors and do not draw the selection box
  6690. # self.plotcanvas.update() # this updates the canvas
  6691. except Exception as e:
  6692. log.error("[ERROR] Something went bad. %s" % str(e))
  6693. return
  6694. def delete_hover_shape(self):
  6695. self.hover_shapes.clear()
  6696. self.hover_shapes.redraw()
  6697. def draw_hover_shape(self, sel_obj, color=None):
  6698. """
  6699. :param sel_obj: the object for which the hover shape must be drawn
  6700. :return:
  6701. """
  6702. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6703. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6704. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6705. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6706. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  6707. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  6708. hover_rect = hover_rect.buffer(-0.1)
  6709. hover_rect = hover_rect.buffer(0.2)
  6710. else:
  6711. hover_rect = hover_rect.buffer(-0.00393)
  6712. hover_rect = hover_rect.buffer(0.00787)
  6713. if color:
  6714. face = Color(color)
  6715. face.alpha = 0.2
  6716. outline = Color(color, alpha=0.8)
  6717. else:
  6718. face = Color(self.defaults['global_sel_fill'])
  6719. face.alpha = 0.2
  6720. outline = self.defaults['global_sel_line']
  6721. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  6722. def delete_selection_shape(self):
  6723. self.move_tool.sel_shapes.clear()
  6724. self.move_tool.sel_shapes.redraw()
  6725. def draw_selection_shape(self, sel_obj, color=None):
  6726. """
  6727. :param sel_obj: the object for which the selection shape must be drawn
  6728. :return:
  6729. """
  6730. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6731. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6732. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6733. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6734. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6735. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  6736. sel_rect = sel_rect.buffer(-0.1)
  6737. sel_rect = sel_rect.buffer(0.2)
  6738. else:
  6739. sel_rect = sel_rect.buffer(-0.00393)
  6740. sel_rect = sel_rect.buffer(0.00787)
  6741. if color:
  6742. face = Color(color, alpha=0.2)
  6743. outline = Color(color, alpha=0.8)
  6744. else:
  6745. face = Color(self.defaults['global_sel_fill'], alpha=0.2)
  6746. outline = Color(self.defaults['global_sel_line'], alpha=0.8)
  6747. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  6748. color=outline,
  6749. face_color=face,
  6750. update=True,
  6751. layer=0,
  6752. tolerance=None))
  6753. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  6754. """
  6755. :param old_coords: old coordinates
  6756. :param coords: new coordinates
  6757. :return:
  6758. """
  6759. if 'color' in kwargs:
  6760. color = kwargs['color']
  6761. else:
  6762. color = self.defaults['global_sel_line']
  6763. if 'face_color' in kwargs:
  6764. face_color = kwargs['face_color']
  6765. else:
  6766. face_color = self.defaults['global_sel_fill']
  6767. if 'face_alpha' in kwargs:
  6768. face_alpha = kwargs['face_alpha']
  6769. else:
  6770. face_alpha = 0.3
  6771. x0, y0 = old_coords
  6772. x1, y1 = coords
  6773. pt1 = (x0, y0)
  6774. pt2 = (x1, y0)
  6775. pt3 = (x1, y1)
  6776. pt4 = (x0, y1)
  6777. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6778. color_t = Color(face_color)
  6779. color_t.alpha = face_alpha
  6780. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  6781. layer=0, tolerance=None)
  6782. def on_file_new_click(self):
  6783. if self.collection.get_list() and self.should_we_save:
  6784. msgbox = QtWidgets.QMessageBox()
  6785. # msgbox.setText("<B>Save changes ...</B>")
  6786. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  6787. "Creating a New project will delete them.\n"
  6788. "Do you want to Save the project?"))
  6789. msgbox.setWindowTitle(_("Save changes"))
  6790. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6791. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6792. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6793. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  6794. msgbox.setDefaultButton(bt_yes)
  6795. msgbox.exec_()
  6796. response = msgbox.clickedButton()
  6797. if response == bt_yes:
  6798. self.on_file_saveprojectas()
  6799. elif response == bt_cancel:
  6800. return
  6801. elif response == bt_no:
  6802. self.on_file_new()
  6803. else:
  6804. self.on_file_new()
  6805. self.inform.emit('[success] %s...' %
  6806. _("New Project created"))
  6807. def on_file_new(self, cli=None):
  6808. """
  6809. Callback for menu item File->New. Returns the application to its
  6810. startup state. This method is thread-safe.
  6811. :return: None
  6812. """
  6813. self.report_usage("on_file_new")
  6814. # Remove everything from memory
  6815. App.log.debug("on_file_new()")
  6816. if self.call_source != 'app':
  6817. self.editor2object(cleanup=True)
  6818. # ## EDITOR section
  6819. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  6820. self.exc_editor = FlatCAMExcEditor(self)
  6821. self.grb_editor = FlatCAMGrbEditor(self)
  6822. # Clear pool
  6823. self.clear_pool()
  6824. for obj in self.collection.get_list():
  6825. # delete shapes left drawn from mark shape_collections, if any
  6826. if isinstance(obj, FlatCAMGerber):
  6827. try:
  6828. obj.mark_shapes.enabled = False
  6829. obj.mark_shapes.clear(update=True)
  6830. except AttributeError:
  6831. pass
  6832. # also delete annotation shapes, if any
  6833. elif isinstance(obj, FlatCAMCNCjob):
  6834. try:
  6835. obj.annotation.enabled = False
  6836. obj.annotation.clear(update=True)
  6837. except AttributeError:
  6838. pass
  6839. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  6840. self.init_tcl()
  6841. self.delete_selection_shape()
  6842. self.collection.delete_all()
  6843. self.setup_component_editor()
  6844. # Clear project filename
  6845. self.project_filename = None
  6846. # Load the application defaults
  6847. self.load_defaults(filename='current_defaults')
  6848. # Re-fresh project options
  6849. self.on_options_app2project()
  6850. # Init Tools
  6851. self.init_tools()
  6852. if cli is None:
  6853. # Close any Tabs opened in the Plot Tab Area section
  6854. for index in range(self.ui.plot_tab_area.count()):
  6855. self.ui.plot_tab_area.closeTab(index)
  6856. # for whatever reason previous command does not close the last tab so I do it manually
  6857. self.ui.plot_tab_area.closeTab(0)
  6858. # # And then add again the Plot Area
  6859. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  6860. self.ui.plot_tab_area.protectTab(0)
  6861. # take the focus of the Notebook on Project Tab.
  6862. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6863. self.set_ui_title(name=_("New Project - Not saved"))
  6864. def obj_properties(self):
  6865. self.report_usage("obj_properties()")
  6866. self.properties_tool.run(toggle=False)
  6867. def on_project_context_save(self):
  6868. obj = self.collection.get_active()
  6869. if type(obj) == FlatCAMGeometry:
  6870. self.on_file_exportdxf()
  6871. elif type(obj) == FlatCAMExcellon:
  6872. self.on_file_saveexcellon()
  6873. elif type(obj) == FlatCAMCNCjob:
  6874. obj.on_exportgcode_button_click()
  6875. elif type(obj) == FlatCAMGerber:
  6876. self.on_file_savegerber()
  6877. def obj_move(self):
  6878. self.report_usage("obj_move()")
  6879. self.move_tool.run(toggle=False)
  6880. def on_fileopengerber(self, checked=None, name=None):
  6881. """
  6882. File menu callback for opening a Gerber.
  6883. :return: None
  6884. """
  6885. self.report_usage("on_fileopengerber")
  6886. App.log.debug("on_fileopengerber()")
  6887. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  6888. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  6889. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  6890. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  6891. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6892. "*.mil);;" \
  6893. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6894. "Allegro Files (*.art);;" \
  6895. "Mentor Files (*.pho *.gdo);;" \
  6896. "All Files (*.*)"
  6897. if name is None:
  6898. try:
  6899. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6900. directory=self.get_last_folder(),
  6901. filter=_filter_)
  6902. except TypeError:
  6903. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6904. filenames = [str(filename) for filename in filenames]
  6905. else:
  6906. filenames = [name]
  6907. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6908. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6909. _("Opening Gerber file.")),
  6910. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6911. color=QtGui.QColor("gray"))
  6912. if len(filenames) == 0:
  6913. self.inform.emit('[WARNING_NOTCL] %s' %
  6914. _("Open Gerber cancelled."))
  6915. else:
  6916. for filename in filenames:
  6917. if filename != '':
  6918. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6919. def on_fileopenexcellon(self, checked=None, name=None):
  6920. """
  6921. File menu callback for opening an Excellon file.
  6922. :return: None
  6923. """
  6924. self.report_usage("on_fileopenexcellon")
  6925. App.log.debug("on_fileopenexcellon()")
  6926. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6927. "All Files (*.*)"
  6928. if name is None:
  6929. try:
  6930. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6931. directory=self.get_last_folder(),
  6932. filter=_filter_)
  6933. except TypeError:
  6934. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6935. filenames = [str(filename) for filename in filenames]
  6936. else:
  6937. filenames = [str(name)]
  6938. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6939. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6940. _("Opening Excellon file.")),
  6941. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6942. color=QtGui.QColor("gray"))
  6943. if len(filenames) == 0:
  6944. self.inform.emit('[WARNING_NOTCL]%s' %
  6945. _(" Open Excellon cancelled."))
  6946. else:
  6947. for filename in filenames:
  6948. if filename != '':
  6949. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6950. def on_fileopengcode(self, checked=None, name=None):
  6951. """
  6952. File menu call back for opening gcode.
  6953. :return: None
  6954. """
  6955. self.report_usage("on_fileopengcode")
  6956. App.log.debug("on_fileopengcode()")
  6957. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6958. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6959. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  6960. "All Files (*.*)"
  6961. if name is None:
  6962. try:
  6963. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6964. directory=self.get_last_folder(),
  6965. filter=_filter_)
  6966. except TypeError:
  6967. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6968. filenames = [str(filename) for filename in filenames]
  6969. else:
  6970. filenames = [name]
  6971. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6972. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6973. _("Opening G-Code file.")),
  6974. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6975. color=QtGui.QColor("gray"))
  6976. if len(filenames) == 0:
  6977. self.inform.emit('[WARNING_NOTCL] %s' %
  6978. _("Open G-Code cancelled."))
  6979. else:
  6980. for filename in filenames:
  6981. if filename != '':
  6982. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename]})
  6983. def on_file_openproject(self, checked=None):
  6984. """
  6985. File menu callback for opening a project.
  6986. :return: None
  6987. """
  6988. self.report_usage("on_file_openproject")
  6989. App.log.debug("on_file_openproject()")
  6990. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6991. try:
  6992. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6993. directory=self.get_last_folder(), filter=_filter_)
  6994. except TypeError:
  6995. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6996. # The Qt methods above will return a QString which can cause problems later.
  6997. # So far json.dump() will fail to serialize it.
  6998. # TODO: Improve the serialization methods and remove this fix.
  6999. filename = str(filename)
  7000. if filename == "":
  7001. self.inform.emit('[WARNING_NOTCL] %s' %
  7002. _("Open Project cancelled."))
  7003. else:
  7004. # self.worker_task.emit({'fcn': self.open_project,
  7005. # 'params': [filename]})
  7006. # The above was failing because open_project() is not
  7007. # thread safe. The new_project()
  7008. self.open_project(filename)
  7009. def on_file_openconfig(self, checked=None):
  7010. """
  7011. File menu callback for opening a config file.
  7012. :return: None
  7013. """
  7014. self.report_usage("on_file_openconfig")
  7015. App.log.debug("on_file_openconfig()")
  7016. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  7017. try:
  7018. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7019. directory=self.data_path, filter=_filter_)
  7020. except TypeError:
  7021. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7022. filter=_filter_)
  7023. if filename == "":
  7024. self.inform.emit('[WARNING_NOTCL] %s' %
  7025. _("Open Config cancelled."))
  7026. else:
  7027. self.open_config_file(filename)
  7028. def on_file_exportsvg(self):
  7029. """
  7030. Callback for menu item File->Export SVG.
  7031. :return: None
  7032. """
  7033. self.report_usage("on_file_exportsvg")
  7034. App.log.debug("on_file_exportsvg()")
  7035. obj = self.collection.get_active()
  7036. if obj is None:
  7037. self.inform.emit('[WARNING_NOTCL] %s' %
  7038. _("No object selected."))
  7039. msg = _("Please Select a Geometry object to export")
  7040. msgbox = QtWidgets.QMessageBox()
  7041. msgbox.setInformativeText(msg)
  7042. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7043. msgbox.setDefaultButton(bt_ok)
  7044. msgbox.exec_()
  7045. return
  7046. # Check for more compatible types and add as required
  7047. if (not isinstance(obj, FlatCAMGeometry)
  7048. and not isinstance(obj, FlatCAMGerber)
  7049. and not isinstance(obj, FlatCAMCNCjob)
  7050. and not isinstance(obj, FlatCAMExcellon)):
  7051. msg = '[ERROR_NOTCL] %s' % \
  7052. _("Only Geometry, Gerber and CNCJob objects can be used.")
  7053. msgbox = QtWidgets.QMessageBox()
  7054. msgbox.setInformativeText(msg)
  7055. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7056. msgbox.setDefaultButton(bt_ok)
  7057. msgbox.exec_()
  7058. return
  7059. name = obj.options["name"]
  7060. _filter = "SVG File (*.svg);;All Files (*.*)"
  7061. try:
  7062. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7063. caption=_("Export SVG"),
  7064. directory=self.get_last_save_folder() + '/' + str(name),
  7065. filter=_filter)
  7066. except TypeError:
  7067. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  7068. filename = str(filename)
  7069. if filename == "":
  7070. self.inform.emit('[WARNING_NOTCL]%s' %
  7071. _(" Export SVG cancelled."))
  7072. return
  7073. else:
  7074. self.export_svg(name, filename)
  7075. if self.defaults["global_open_style"] is False:
  7076. self.file_opened.emit("SVG", filename)
  7077. self.file_saved.emit("SVG", filename)
  7078. def on_file_exportpng(self):
  7079. self.report_usage("on_file_exportpng")
  7080. App.log.debug("on_file_exportpng()")
  7081. self.date = str(datetime.today()).rpartition('.')[0]
  7082. self.date = ''.join(c for c in self.date if c not in ':-')
  7083. self.date = self.date.replace(' ', '_')
  7084. image = _screenshot()
  7085. data = np.asarray(image)
  7086. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  7087. self.inform.emit('[[WARNING_NOTCL]] %s' %
  7088. _('Data must be a 3D array with last dimension 3 or 4'))
  7089. return
  7090. filter_ = "PNG File (*.png);;All Files (*.*)"
  7091. try:
  7092. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7093. caption=_("Export PNG Image"),
  7094. directory=self.get_last_save_folder() + '/png_' + self.date,
  7095. filter=filter_)
  7096. except TypeError:
  7097. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  7098. filename = str(filename)
  7099. if filename == "":
  7100. self.inform.emit(_("Export PNG cancelled."))
  7101. return
  7102. else:
  7103. write_png(filename, data)
  7104. if self.defaults["global_open_style"] is False:
  7105. self.file_opened.emit("png", filename)
  7106. self.file_saved.emit("png", filename)
  7107. def on_file_savegerber(self):
  7108. """
  7109. Callback for menu item in Project context menu.
  7110. :return: None
  7111. """
  7112. self.report_usage("on_file_savegerber")
  7113. App.log.debug("on_file_savegerber()")
  7114. obj = self.collection.get_active()
  7115. if obj is None:
  7116. self.inform.emit('[WARNING_NOTCL] %s' %
  7117. _("No object selected. Please select an Gerber object to export."))
  7118. return
  7119. # Check for more compatible types and add as required
  7120. if not isinstance(obj, FlatCAMGerber):
  7121. self.inform.emit('[ERROR_NOTCL] %s' %
  7122. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7123. return
  7124. name = self.collection.get_active().options["name"]
  7125. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  7126. try:
  7127. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7128. caption="Save Gerber source file",
  7129. directory=self.get_last_save_folder() + '/' + name,
  7130. filter=_filter)
  7131. except TypeError:
  7132. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  7133. filename = str(filename)
  7134. if filename == "":
  7135. self.inform.emit('[WARNING_NOTCL] %s' %
  7136. _("Save Gerber source file cancelled."))
  7137. return
  7138. else:
  7139. self.save_source_file(name, filename)
  7140. if self.defaults["global_open_style"] is False:
  7141. self.file_opened.emit("Gerber", filename)
  7142. self.file_saved.emit("Gerber", filename)
  7143. def on_file_saveexcellon(self):
  7144. """
  7145. Callback for menu item in project context menu.
  7146. :return: None
  7147. """
  7148. self.report_usage("on_file_saveexcellon")
  7149. App.log.debug("on_file_saveexcellon()")
  7150. obj = self.collection.get_active()
  7151. if obj is None:
  7152. self.inform.emit('[WARNING_NOTCL] %s' %
  7153. _("No object selected. Please select an Excellon object to export."))
  7154. return
  7155. # Check for more compatible types and add as required
  7156. if not isinstance(obj, FlatCAMExcellon):
  7157. self.inform.emit('[ERROR_NOTCL] %s' %
  7158. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7159. return
  7160. name = self.collection.get_active().options["name"]
  7161. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7162. try:
  7163. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7164. caption=_("Save Excellon source file"),
  7165. directory=self.get_last_save_folder() + '/' + name,
  7166. filter=_filter)
  7167. except TypeError:
  7168. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  7169. filename = str(filename)
  7170. if filename == "":
  7171. self.inform.emit('[WARNING_NOTCL] %s' %
  7172. _("Saving Excellon source file cancelled."))
  7173. return
  7174. else:
  7175. self.save_source_file(name, filename)
  7176. if self.defaults["global_open_style"] is False:
  7177. self.file_opened.emit("Excellon", filename)
  7178. self.file_saved.emit("Excellon", filename)
  7179. def on_file_exportexcellon(self):
  7180. """
  7181. Callback for menu item File->Export->Excellon.
  7182. :return: None
  7183. """
  7184. self.report_usage("on_file_exportexcellon")
  7185. App.log.debug("on_file_exportexcellon()")
  7186. obj = self.collection.get_active()
  7187. if obj is None:
  7188. self.inform.emit('[WARNING_NOTCL] %s' %
  7189. _("No object selected. Please Select an Excellon object to export."))
  7190. return
  7191. # Check for more compatible types and add as required
  7192. if not isinstance(obj, FlatCAMExcellon):
  7193. self.inform.emit('[ERROR_NOTCL] %s' %
  7194. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7195. return
  7196. name = self.collection.get_active().options["name"]
  7197. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7198. try:
  7199. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7200. caption=_("Export Excellon"),
  7201. directory=self.get_last_save_folder() + '/' + name,
  7202. filter=_filter)
  7203. except TypeError:
  7204. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  7205. filename = str(filename)
  7206. if filename == "":
  7207. self.inform.emit('[WARNING_NOTCL] %s' %
  7208. _("Export Excellon cancelled."))
  7209. return
  7210. else:
  7211. self.export_excellon(name, filename)
  7212. if self.defaults["global_open_style"] is False:
  7213. self.file_opened.emit("Excellon", filename)
  7214. self.file_saved.emit("Excellon", filename)
  7215. def on_file_exportgerber(self):
  7216. """
  7217. Callback for menu item File->Export->Gerber.
  7218. :return: None
  7219. """
  7220. self.report_usage("on_file_exportgerber")
  7221. App.log.debug("on_file_exportgerber()")
  7222. obj = self.collection.get_active()
  7223. if obj is None:
  7224. self.inform.emit('[WARNING_NOTCL] %s' %
  7225. _("No object selected. Please Select an Gerber object to export."))
  7226. return
  7227. # Check for more compatible types and add as required
  7228. if not isinstance(obj, FlatCAMGerber):
  7229. self.inform.emit('[ERROR_NOTCL] %s' %
  7230. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7231. return
  7232. name = self.collection.get_active().options["name"]
  7233. _filter_ = "Gerber File (*.GBR);;All Files (*.*)"
  7234. try:
  7235. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7236. caption=_("Export Gerber"),
  7237. directory=self.get_last_save_folder() + '/' + name,
  7238. filter=_filter_)
  7239. except TypeError:
  7240. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  7241. filename = str(filename)
  7242. if filename == "":
  7243. self.inform.emit('[WARNING_NOTCL] %s' %
  7244. _("Export Gerber cancelled."))
  7245. return
  7246. else:
  7247. self.export_gerber(name, filename)
  7248. if self.defaults["global_open_style"] is False:
  7249. self.file_opened.emit("Gerber", filename)
  7250. self.file_saved.emit("Gerber", filename)
  7251. def on_file_exportdxf(self):
  7252. """
  7253. Callback for menu item File->Export DXF.
  7254. :return: None
  7255. """
  7256. self.report_usage("on_file_exportdxf")
  7257. App.log.debug("on_file_exportdxf()")
  7258. obj = self.collection.get_active()
  7259. if obj is None:
  7260. self.inform.emit('[WARNING_NOTCL] %s' %
  7261. _("No object selected."))
  7262. msg = _("Please Select a Geometry object to export")
  7263. msgbox = QtWidgets.QMessageBox()
  7264. msgbox.setInformativeText(msg)
  7265. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7266. msgbox.setDefaultButton(bt_ok)
  7267. msgbox.exec_()
  7268. return
  7269. # Check for more compatible types and add as required
  7270. if not isinstance(obj, FlatCAMGeometry):
  7271. msg = '[ERROR_NOTCL] %s' % \
  7272. _("Only Geometry objects can be used.")
  7273. msgbox = QtWidgets.QMessageBox()
  7274. msgbox.setInformativeText(msg)
  7275. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7276. msgbox.setDefaultButton(bt_ok)
  7277. msgbox.exec_()
  7278. return
  7279. name = self.collection.get_active().options["name"]
  7280. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  7281. try:
  7282. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7283. caption=_("Export DXF"),
  7284. directory=self.get_last_save_folder() + '/' + name,
  7285. filter=_filter_)
  7286. except TypeError:
  7287. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  7288. filter=_filter_)
  7289. filename = str(filename)
  7290. if filename == "":
  7291. self.inform.emit('[WARNING_NOTCL] %s' %
  7292. _("Export DXF cancelled."))
  7293. return
  7294. else:
  7295. self.export_dxf(name, filename)
  7296. if self.defaults["global_open_style"] is False:
  7297. self.file_opened.emit("DXF", filename)
  7298. self.file_saved.emit("DXF", filename)
  7299. def on_file_importsvg(self, type_of_obj):
  7300. """
  7301. Callback for menu item File->Import SVG.
  7302. :param type_of_obj: to import the SVG as Geometry or as Gerber
  7303. :type type_of_obj: str
  7304. :return: None
  7305. """
  7306. self.report_usage("on_file_importsvg")
  7307. App.log.debug("on_file_importsvg()")
  7308. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  7309. try:
  7310. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7311. directory=self.get_last_folder(), filter=_filter_)
  7312. except TypeError:
  7313. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7314. filter=_filter_)
  7315. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  7316. type_of_obj = "geometry"
  7317. filenames = [str(filename) for filename in filenames]
  7318. if len(filenames) == 0:
  7319. self.inform.emit('[WARNING_NOTCL] %s' %
  7320. _("Open SVG cancelled."))
  7321. else:
  7322. for filename in filenames:
  7323. if filename != '':
  7324. self.worker_task.emit({'fcn': self.import_svg,
  7325. 'params': [filename, type_of_obj]})
  7326. def on_file_importdxf(self, type_of_obj):
  7327. """
  7328. Callback for menu item File->Import DXF.
  7329. :param type_of_obj: to import the DXF as Geometry or as Gerber
  7330. :type type_of_obj: str
  7331. :return: None
  7332. """
  7333. self.report_usage("on_file_importdxf")
  7334. App.log.debug("on_file_importdxf()")
  7335. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  7336. try:
  7337. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7338. directory=self.get_last_folder(),
  7339. filter=_filter_)
  7340. except TypeError:
  7341. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7342. filter=_filter_)
  7343. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  7344. type_of_obj = "geometry"
  7345. filenames = [str(filename) for filename in filenames]
  7346. if len(filenames) == 0:
  7347. self.inform.emit('[WARNING_NOTCL] %s' %
  7348. _("Open DXF cancelled."))
  7349. else:
  7350. for filename in filenames:
  7351. if filename != '':
  7352. self.worker_task.emit({'fcn': self.import_dxf,
  7353. 'params': [filename, type_of_obj]})
  7354. # ###############################################################################################################
  7355. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  7356. # ###############################################################################################################
  7357. def init_code_editor(self, name):
  7358. # Signals section
  7359. # Disconnect the old signals
  7360. try:
  7361. self.ui.buttonOpen.clicked.disconnect()
  7362. except TypeError:
  7363. pass
  7364. try:
  7365. self.ui.buttonSave.clicked.disconnect()
  7366. except TypeError:
  7367. pass
  7368. # add the tab if it was closed
  7369. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, '%s' % name)
  7370. self.ui.cncjob_tab.setObjectName('cncjob_tab')
  7371. # delete the absolute and relative position and messages in the infobar
  7372. self.ui.position_label.setText("")
  7373. self.ui.rel_position_label.setText("")
  7374. # first clear previous text in text editor (if any)
  7375. self.ui.code_editor.clear()
  7376. self.ui.code_editor.setReadOnly(False)
  7377. self.toggle_codeeditor = True
  7378. self.ui.code_editor.completer_enable = False
  7379. self.ui.buttonRun.hide()
  7380. # make sure to keep a reference to the code editor
  7381. self.reference_code_editor = self.ui.code_editor
  7382. # Switch plot_area to CNCJob tab
  7383. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  7384. def on_view_source(self):
  7385. self.inform.emit('%s' %
  7386. _("Viewing the source code of the selected object."))
  7387. self.proc_container.view.set_busy(_("Loading..."))
  7388. try:
  7389. obj = self.collection.get_active()
  7390. except Exception as e:
  7391. log.debug("App.on_view_source() --> %s" % str(e))
  7392. self.inform.emit('[WARNING_NOTCL] %s' %
  7393. _("Select an Gerber or Excellon file to view it's source file."))
  7394. return 'fail'
  7395. if obj.kind == 'gerber':
  7396. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  7397. elif obj.kind == 'excellon':
  7398. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  7399. elif obj.kind == 'cncjob':
  7400. "GCode Files (*.NC);;All Files (*.*)"
  7401. else:
  7402. flt = "All Files (*.*)"
  7403. self.init_code_editor(name=_("Source Editor"))
  7404. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  7405. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  7406. # then append the text from GCode to the text editor
  7407. if obj.kind == 'cncjob':
  7408. try:
  7409. file = obj.export_gcode(
  7410. preamble=self.defaults["cncjob_prepend"],
  7411. postamble=self.defaults["cncjob_append"],
  7412. to_file=True)
  7413. if file == 'fail':
  7414. return 'fail'
  7415. except AttributeError:
  7416. self.inform.emit('[WARNING_NOTCL] %s' %
  7417. _("There is no selected object for which to see it's source file code."))
  7418. return 'fail'
  7419. else:
  7420. try:
  7421. file = StringIO(obj.source_file)
  7422. except AttributeError:
  7423. self.inform.emit('[WARNING_NOTCL] %s' %
  7424. _("There is no selected object for which to see it's source file code."))
  7425. return 'fail'
  7426. self.ui.cncjob_frame.hide()
  7427. try:
  7428. for line in file:
  7429. QtWidgets.QApplication.processEvents()
  7430. proc_line = str(line).strip('\n')
  7431. self.ui.code_editor.append(proc_line)
  7432. except Exception as e:
  7433. log.debug('App.on_view_source() -->%s' % str(e))
  7434. self.inform.emit('[ERROR] %s: %s' %
  7435. (_('Failed to load the source code for the selected object'), str(e)))
  7436. return
  7437. self.handleTextChanged()
  7438. self.ui.cncjob_frame.show()
  7439. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  7440. self.proc_container.view.set_idle()
  7441. # self.ui.show()
  7442. def on_toggle_code_editor(self):
  7443. self.report_usage("on_toggle_code_editor()")
  7444. if self.toggle_codeeditor is False:
  7445. self.init_code_editor(name=_("Code Editor"))
  7446. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen())
  7447. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode())
  7448. else:
  7449. for idx in range(self.ui.plot_tab_area.count()):
  7450. if self.ui.plot_tab_area.widget(idx).objectName() == "cncjob_tab":
  7451. self.ui.plot_tab_area.closeTab(idx)
  7452. break
  7453. self.toggle_codeeditor = False
  7454. def on_filenewscript(self, silent=False):
  7455. """
  7456. Will create a new script file and open it in the Code Editor
  7457. :param silent: if True will not display status messages
  7458. :return: None
  7459. """
  7460. if silent is False:
  7461. self.inform.emit('[success] %s' %
  7462. _("New TCL script file created in Code Editor."))
  7463. flt = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  7464. self.init_code_editor(name=_("Script Editor"))
  7465. self.ui.code_editor.completer_enable = True
  7466. self.ui.code_editor.append(_(
  7467. "#\n"
  7468. "# CREATE A NEW FLATCAM TCL SCRIPT\n"
  7469. "# TCL Tutorial here: https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n"
  7470. "#\n\n"
  7471. "# FlatCAM commands list:\n"
  7472. "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, AlignDrillGrid, ClearShell, ClearCopper,\n"
  7473. "# Cncjob, Cutout, Delete, Drillcncjob, ExportGcode, ExportSVG, Exteriors, GeoCutout, GeoUnion, GetNames,\n"
  7474. "# GetSys, ImportSvg, Interiors, Isolate, Follow, JoinExcellon, JoinGeometry, ListSys, MillDrills,\n"
  7475. "# MillSlots, Mirror, New, NewGeometry, Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n"
  7476. "# Options, Paint, Panelize, Plot, SaveProject, SaveSys, Scale, SetActive, SetSys, Skew, SubtractPoly,\n"
  7477. "# SubtractRectangle, Version, WriteGCode\n"
  7478. "#\n\n"
  7479. ))
  7480. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  7481. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  7482. self.ui.buttonRun.show()
  7483. try:
  7484. self.ui.buttonRun.clicked.disconnect(self.handleRunCode)
  7485. except TypeError:
  7486. pass
  7487. self.ui.buttonRun.clicked.connect(self.handleRunCode)
  7488. self.handleTextChanged()
  7489. self.ui.code_editor.show()
  7490. def on_fileopenscript(self, name=None, silent=False):
  7491. """
  7492. Will open a Tcl script file into the Code Editor
  7493. :param silent: if True will not display status messages
  7494. :param name: name of a Tcl script file to open
  7495. :return:
  7496. """
  7497. if name:
  7498. filename = name
  7499. else:
  7500. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  7501. try:
  7502. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"),
  7503. directory=self.get_last_folder(), filter=_filter_)
  7504. except TypeError:
  7505. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"), filter=_filter_)
  7506. # The Qt methods above will return a QString which can cause problems later.
  7507. # So far json.dump() will fail to serialize it.
  7508. # TODO: Improve the serialization methods and remove this fix.
  7509. filename = str(filename)
  7510. if filename == "":
  7511. if silent is False:
  7512. self.inform.emit('[WARNING_NOTCL] %s' %
  7513. _("Open TCL script cancelled."))
  7514. else:
  7515. self.on_filenewscript()
  7516. try:
  7517. with open(filename, "r") as opened_script:
  7518. try:
  7519. for line in opened_script:
  7520. proc_line = str(line).strip('\n')
  7521. self.ui.code_editor.append(proc_line)
  7522. except Exception as e:
  7523. log.debug('App.on_fileopenscript() -->%s' % str(e))
  7524. if silent is False:
  7525. self.inform.emit('[ERROR] %s %s' %
  7526. (_('App.on_fileopenscript() -->'), str(e)))
  7527. return
  7528. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  7529. self.handleTextChanged()
  7530. if silent is False:
  7531. self.inform.emit('[success] %s' %
  7532. _("TCL script file opened in Code Editor."))
  7533. # self.ui.show()
  7534. except Exception as e:
  7535. log.debug("App.on_fileopenscript() -> %s" % str(e))
  7536. def on_filerunscript(self, name=None, silent=False):
  7537. """
  7538. File menu callback for loading and running a TCL script.
  7539. :param silent: if True will not display status messages
  7540. :param name: name of a Tcl script file to be run by FlatCAM
  7541. :return: None
  7542. """
  7543. self.report_usage("on_filerunscript")
  7544. App.log.debug("on_file_runscript()")
  7545. if name:
  7546. filename = name
  7547. if self.cmd_line_headless != 1:
  7548. self.splash.showMessage('%s: %ssec\n%s' %
  7549. (_("Canvas initialization started.\n"
  7550. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7551. _("Executing FlatCAMScript file.")
  7552. ),
  7553. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7554. color=QtGui.QColor("gray"))
  7555. else:
  7556. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  7557. try:
  7558. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  7559. directory=self.get_last_folder(), filter=_filter_)
  7560. except TypeError:
  7561. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  7562. # The Qt methods above will return a QString which can cause problems later.
  7563. # So far json.dump() will fail to serialize it.
  7564. # TODO: Improve the serialization methods and remove this fix.
  7565. filename = str(filename)
  7566. if filename == "":
  7567. if silent is False:
  7568. self.inform.emit('[WARNING_NOTCL] %s' %
  7569. _("Run TCL script cancelled."))
  7570. else:
  7571. if self.cmd_line_headless != 1:
  7572. if self.ui.shell_dock.isHidden():
  7573. self.ui.shell_dock.show()
  7574. try:
  7575. with open(filename, "r") as tcl_script:
  7576. cmd_line_shellfile_content = tcl_script.read()
  7577. if self.cmd_line_headless != 1:
  7578. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  7579. else:
  7580. self.shell._sysShell.exec_command(cmd_line_shellfile_content, no_echo=True)
  7581. if silent is False:
  7582. self.inform.emit('[success] %s' %
  7583. _("TCL script file opened in Code Editor and executed."))
  7584. except Exception as e:
  7585. log.debug("App.on_filerunscript() -> %s" % str(e))
  7586. sys.exit(2)
  7587. def on_file_saveproject(self, silent=False):
  7588. """
  7589. Callback for menu item File->Save Project. Saves the project to
  7590. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  7591. if set to None. The project is saved by calling ``self.save_project()``.
  7592. :param silent: if True will not display status messages
  7593. :return: None
  7594. """
  7595. self.report_usage("on_file_saveproject")
  7596. if self.project_filename is None:
  7597. self.on_file_saveprojectas()
  7598. else:
  7599. self.worker_task.emit({'fcn': self.save_project,
  7600. 'params': [self.project_filename, silent]})
  7601. if self.defaults["global_open_style"] is False:
  7602. self.file_opened.emit("project", self.project_filename)
  7603. self.file_saved.emit("project", self.project_filename)
  7604. self.set_ui_title(name=self.project_filename)
  7605. self.should_we_save = False
  7606. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  7607. """
  7608. Callback for menu item File->Save Project As... Opens a file
  7609. chooser and saves the project to the given file via
  7610. ``self.save_project()``.
  7611. :param make_copy if to be create a copy of the project; boolean
  7612. :param use_thread: if to be run in a separate thread; boolean
  7613. :param quit_action: if to be followed by quiting the application; boolean
  7614. :return: None
  7615. """
  7616. self.report_usage("on_file_saveprojectas")
  7617. self.date = str(datetime.today()).rpartition('.')[0]
  7618. self.date = ''.join(c for c in self.date if c not in ':-')
  7619. self.date = self.date.replace(' ', '_')
  7620. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  7621. try:
  7622. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7623. caption=_("Save Project As ..."),
  7624. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  7625. filter=filter_)
  7626. except TypeError:
  7627. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  7628. filename = str(filename)
  7629. if filename == '':
  7630. self.inform.emit('[WARNING_NOTCL] %s' %
  7631. _("Save Project cancelled."))
  7632. return
  7633. try:
  7634. f = open(filename, 'r')
  7635. f.close()
  7636. except IOError:
  7637. pass
  7638. if use_thread is True:
  7639. self.worker_task.emit({'fcn': self.save_project,
  7640. 'params': [filename, quit_action]})
  7641. else:
  7642. self.save_project(filename, quit_action)
  7643. # self.save_project(filename)
  7644. if self.defaults["global_open_style"] is False:
  7645. self.file_opened.emit("project", filename)
  7646. self.file_saved.emit("project", filename)
  7647. if not make_copy:
  7648. self.project_filename = filename
  7649. self.set_ui_title(name=self.project_filename)
  7650. self.should_we_save = False
  7651. def export_svg(self, obj_name, filename, scale_factor=0.00):
  7652. """
  7653. Exports a Geometry Object to an SVG file.
  7654. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7655. :param filename: Path to the SVG file to save to.
  7656. :param scale_factor: factor by which to change/scale the thickness of the features
  7657. :return:
  7658. """
  7659. self.report_usage("export_svg()")
  7660. if filename is None:
  7661. filename = self.defaults["global_last_save_folder"]
  7662. self.log.debug("export_svg()")
  7663. try:
  7664. obj = self.collection.get_by_name(str(obj_name))
  7665. except:
  7666. # TODO: The return behavior has not been established... should raise exception?
  7667. return "Could not retrieve object: %s" % obj_name
  7668. with self.proc_container.new(_("Exporting SVG")) as proc:
  7669. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7670. # Determine bounding area for svg export
  7671. bounds = obj.bounds()
  7672. size = obj.size()
  7673. # Convert everything to strings for use in the xml doc
  7674. svgwidth = str(size[0])
  7675. svgheight = str(size[1])
  7676. minx = str(bounds[0])
  7677. miny = str(bounds[1] - size[1])
  7678. uom = obj.units.lower()
  7679. # Add a SVG Header and footer to the svg output from shapely
  7680. # The transform flips the Y Axis so that everything renders
  7681. # properly within svg apps such as inkscape
  7682. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7683. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7684. svg_header += 'width="' + svgwidth + uom + '" '
  7685. svg_header += 'height="' + svgheight + uom + '" '
  7686. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7687. svg_header += '<g transform="scale(1,-1)">'
  7688. svg_footer = '</g> </svg>'
  7689. svg_elem = svg_header + exported_svg + svg_footer
  7690. # Parse the xml through a xml parser just to add line feeds
  7691. # and to make it look more pretty for the output
  7692. svgcode = parse_xml_string(svg_elem)
  7693. try:
  7694. with open(filename, 'w') as fp:
  7695. fp.write(svgcode.toprettyxml())
  7696. except PermissionError:
  7697. self.inform.emit('[WARNING] %s' %
  7698. _("Permission denied, saving not possible.\n"
  7699. "Most likely another app is holding the file open and not accessible."))
  7700. return 'fail'
  7701. if self.defaults["global_open_style"] is False:
  7702. self.file_opened.emit("SVG", filename)
  7703. self.file_saved.emit("SVG", filename)
  7704. self.inform.emit('[success] %s: %s' %
  7705. (_("SVG file exported to"), filename))
  7706. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  7707. """
  7708. Exports a Geometry Object to an SVG file in negative.
  7709. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7710. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  7711. :param filename: Path to the SVG file to save to.
  7712. :param boundary: thickness of a black border to surround all the features
  7713. :param scale_factor: factor by which to change/scale the thickness of the features
  7714. :param use_thread: if to be run in a separate thread; boolean
  7715. :return:
  7716. """
  7717. self.report_usage("export_negative()")
  7718. if filename is None:
  7719. filename = self.defaults["global_last_save_folder"]
  7720. self.log.debug("export_svg() negative")
  7721. try:
  7722. obj = self.collection.get_by_name(str(obj_name))
  7723. except:
  7724. # TODO: The return behavior has not been established... should raise exception?
  7725. return "Could not retrieve object: %s" % obj_name
  7726. try:
  7727. box = self.collection.get_by_name(str(box_name))
  7728. except:
  7729. # TODO: The return behavior has not been established... should raise exception?
  7730. return "Could not retrieve object: %s" % box_name
  7731. if box is None:
  7732. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  7733. (_("No object Box. Using instead"), obj))
  7734. box = obj
  7735. def make_negative_film():
  7736. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7737. # Determine bounding area for svg export
  7738. bounds = box.bounds()
  7739. size = box.size()
  7740. uom = obj.units.lower()
  7741. # Convert everything to strings for use in the xml doc
  7742. svgwidth = str(size[0] + (2 * boundary))
  7743. svgheight = str(size[1] + (2 * boundary))
  7744. minx = str(bounds[0] - boundary)
  7745. miny = str(bounds[1] + boundary + size[1])
  7746. miny_rect = str(bounds[1] - boundary)
  7747. # Add a SVG Header and footer to the svg output from shapely
  7748. # The transform flips the Y Axis so that everything renders
  7749. # properly within svg apps such as inkscape
  7750. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7751. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7752. svg_header += 'width="' + svgwidth + uom + '" '
  7753. svg_header += 'height="' + svgheight + uom + '" '
  7754. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7755. svg_header += '>'
  7756. svg_header += '<g transform="scale(1,-1)">'
  7757. svg_footer = '</g> </svg>'
  7758. # Change the attributes of the exported SVG
  7759. # We don't need stroke-width - wrong, we do when we have lines with certain width
  7760. # We set opacity to maximum
  7761. # We set the color to WHITE
  7762. root = ET.fromstring(exported_svg)
  7763. for child in root:
  7764. child.set('fill', '#FFFFFF')
  7765. child.set('opacity', '1.0')
  7766. child.set('stroke', '#FFFFFF')
  7767. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  7768. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  7769. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  7770. first_svg_elem_tag = 'rect'
  7771. first_svg_elem_attribs = {
  7772. 'x': minx,
  7773. 'y': miny_rect,
  7774. 'width': svgwidth,
  7775. 'height': svgheight,
  7776. 'id': 'neg_rect',
  7777. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  7778. }
  7779. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  7780. exported_svg = ET.tostring(root)
  7781. svg_elem = svg_header + str(exported_svg) + svg_footer
  7782. # Parse the xml through a xml parser just to add line feeds
  7783. # and to make it look more pretty for the output
  7784. doc = parse_xml_string(svg_elem)
  7785. try:
  7786. with open(filename, 'w') as fp:
  7787. fp.write(doc.toprettyxml())
  7788. except PermissionError:
  7789. self.inform.emit('[WARNING] %s' %
  7790. _("Permission denied, saving not possible.\n"
  7791. "Most likely another app is holding the file open and not accessible."))
  7792. return 'fail'
  7793. if self.defaults["global_open_style"] is False:
  7794. self.file_opened.emit("SVG", filename)
  7795. self.file_saved.emit("SVG", filename)
  7796. self.inform.emit('[success] %s: %s' %
  7797. (_("SVG file exported to"), filename))
  7798. if use_thread is True:
  7799. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  7800. def job_thread_film(app_obj):
  7801. try:
  7802. make_negative_film()
  7803. except Exception as e:
  7804. proc.done()
  7805. return
  7806. proc.done()
  7807. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  7808. else:
  7809. make_negative_film()
  7810. def export_svg_positive(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  7811. """
  7812. Exports a Geometry Object to an SVG file in positive black.
  7813. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7814. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  7815. :param filename: Path to the SVG file to save to.
  7816. :param scale_factor: factor by which to change/scale the thickness of the features
  7817. :param use_thread: if to be run in a separate thread; boolean
  7818. :return:
  7819. """
  7820. self.report_usage("export_svg_positive()")
  7821. if filename is None:
  7822. filename = self.defaults["global_last_save_folder"]
  7823. self.log.debug("export_svg() black")
  7824. try:
  7825. obj = self.collection.get_by_name(str(obj_name))
  7826. except:
  7827. # TODO: The return behavior has not been established... should raise exception?
  7828. return "Could not retrieve object: %s" % obj_name
  7829. try:
  7830. box = self.collection.get_by_name(str(box_name))
  7831. except:
  7832. # TODO: The return behavior has not been established... should raise exception?
  7833. return "Could not retrieve object: %s" % box_name
  7834. if box is None:
  7835. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  7836. (_("No object Box. Using instead"), obj))
  7837. box = obj
  7838. def make_positive_film():
  7839. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7840. self.progress.emit(40)
  7841. # Change the attributes of the exported SVG
  7842. # We don't need stroke-width
  7843. # We set opacity to maximum
  7844. # We set the colour to WHITE
  7845. root = ET.fromstring(exported_svg)
  7846. for child in root:
  7847. child.set('fill', str(self.defaults['tools_film_color']))
  7848. child.set('opacity', '1.0')
  7849. child.set('stroke', str(self.defaults['tools_film_color']))
  7850. exported_svg = ET.tostring(root)
  7851. # Determine bounding area for svg export
  7852. bounds = box.bounds()
  7853. size = box.size()
  7854. # This contain the measure units
  7855. uom = obj.units.lower()
  7856. # Define a boundary around SVG of about 1.0mm (~39mils)
  7857. if uom in "mm":
  7858. boundary = 1.0
  7859. else:
  7860. boundary = 0.0393701
  7861. self.progress.emit(80)
  7862. # Convert everything to strings for use in the xml doc
  7863. svgwidth = str(size[0] + (2 * boundary))
  7864. svgheight = str(size[1] + (2 * boundary))
  7865. minx = str(bounds[0] - boundary)
  7866. miny = str(bounds[1] + boundary + size[1])
  7867. self.log.debug(minx)
  7868. self.log.debug(miny)
  7869. # Add a SVG Header and footer to the svg output from shapely
  7870. # The transform flips the Y Axis so that everything renders
  7871. # properly within svg apps such as inkscape
  7872. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7873. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7874. svg_header += 'width="' + svgwidth + uom + '" '
  7875. svg_header += 'height="' + svgheight + uom + '" '
  7876. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7877. svg_header += '>'
  7878. svg_header += '<g transform="scale(1,-1)">'
  7879. svg_footer = '</g> </svg>'
  7880. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  7881. self.progress.emit(90)
  7882. # Parse the xml through a xml parser just to add line feeds
  7883. # and to make it look more pretty for the output
  7884. doc = parse_xml_string(svg_elem)
  7885. try:
  7886. with open(filename, 'w') as fp:
  7887. fp.write(doc.toprettyxml())
  7888. except PermissionError:
  7889. self.inform.emit('[WARNING] %s' %
  7890. _("Permission denied, saving not possible.\n"
  7891. "Most likely another app is holding the file open and not accessible."))
  7892. return 'fail'
  7893. self.progress.emit(100)
  7894. if self.defaults["global_open_style"] is False:
  7895. self.file_opened.emit("SVG", filename)
  7896. self.file_saved.emit("SVG", filename)
  7897. self.inform.emit('[success] %s: %s' %
  7898. (_("SVG file exported to"), filename))
  7899. if use_thread is True:
  7900. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  7901. def job_thread_film(app_obj):
  7902. try:
  7903. make_positive_film()
  7904. except Exception as e:
  7905. proc.done()
  7906. return
  7907. proc.done()
  7908. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  7909. else:
  7910. make_positive_film()
  7911. def save_source_file(self, obj_name, filename, use_thread=True):
  7912. """
  7913. Exports a FlatCAM Object to an Gerber/Excellon file.
  7914. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  7915. :param filename: Path to the Gerber file to save to.
  7916. :param use_thread: if to be run in a separate thread
  7917. :return:
  7918. """
  7919. self.report_usage("save source file()")
  7920. if filename is None:
  7921. filename = self.defaults["global_last_save_folder"]
  7922. self.log.debug("save source file()")
  7923. obj = self.collection.get_by_name(obj_name)
  7924. file_string = StringIO(obj.source_file)
  7925. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7926. try:
  7927. with open(filename, 'w') as file:
  7928. file.writelines('G04*\n')
  7929. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  7930. (obj.kind.upper(), str(self.version), str(self.version_date)))
  7931. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  7932. file.writelines('G04 Created on : %s*\n' % time_string)
  7933. for line in file_string:
  7934. file.writelines(line)
  7935. except PermissionError:
  7936. self.inform.emit('[WARNING] %s' %
  7937. _("Permission denied, saving not possible.\n"
  7938. "Most likely another app is holding the file open and not accessible."))
  7939. return 'fail'
  7940. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7941. """
  7942. Exports a Excellon Object to an Excellon file.
  7943. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7944. :param filename: Path to the Excellon file to save to.
  7945. :param use_thread: if to be run in a separate thread
  7946. :return:
  7947. """
  7948. self.report_usage("export_excellon()")
  7949. if filename is None:
  7950. filename = self.defaults["global_last_save_folder"]
  7951. self.log.debug("export_excellon()")
  7952. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7953. self.defaults["excellon_exp_decimals"]
  7954. )
  7955. units = ''
  7956. if local_use is None:
  7957. try:
  7958. obj = self.collection.get_by_name(str(obj_name))
  7959. except:
  7960. # TODO: The return behavior has not been established... should raise exception?
  7961. return "Could not retrieve object: %s" % obj_name
  7962. else:
  7963. obj = local_use
  7964. # updated units
  7965. eunits = self.defaults["excellon_exp_units"]
  7966. ewhole = self.defaults["excellon_exp_integer"]
  7967. efract = self.defaults["excellon_exp_decimals"]
  7968. ezeros = self.defaults["excellon_exp_zeros"]
  7969. eformat = self.defaults["excellon_exp_format"]
  7970. slot_type = self.defaults["excellon_exp_slot_type"]
  7971. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7972. if fc_units == 'MM':
  7973. factor = 1 if eunits == 'METRIC' else 0.03937
  7974. else:
  7975. factor = 25.4 if eunits == 'METRIC' else 1
  7976. def make_excellon():
  7977. try:
  7978. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7979. header = 'M48\n'
  7980. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7981. (str(self.version), str(self.version_date))
  7982. header += ';Filename: %s' % str(obj_name) + '\n'
  7983. header += ';Created on : %s' % time_str + '\n'
  7984. if eformat == 'dec':
  7985. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7986. header += eunits + '\n'
  7987. for tool in obj.tools:
  7988. if eunits == 'METRIC':
  7989. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7990. tool=str(tool),
  7991. dec=2)
  7992. else:
  7993. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7994. tool=str(tool),
  7995. dec=4)
  7996. else:
  7997. if ezeros == 'LZ':
  7998. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7999. form='ndec', e_zeros='LZ', factor=factor,
  8000. slot_type=slot_type)
  8001. header += '%s,%s\n' % (eunits, 'LZ')
  8002. header += format_exc
  8003. for tool in obj.tools:
  8004. if eunits == 'METRIC':
  8005. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8006. tool=str(tool),
  8007. dec=2)
  8008. else:
  8009. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8010. tool=str(tool),
  8011. dec=4)
  8012. else:
  8013. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8014. form='ndec', e_zeros='TZ', factor=factor,
  8015. slot_type=slot_type)
  8016. header += '%s,%s\n' % (eunits, 'TZ')
  8017. header += format_exc
  8018. for tool in obj.tools:
  8019. if eunits == 'METRIC':
  8020. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8021. tool=str(tool),
  8022. dec=2)
  8023. else:
  8024. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8025. tool=str(tool),
  8026. dec=4)
  8027. header += '%\n'
  8028. footer = 'M30\n'
  8029. exported_excellon = header
  8030. exported_excellon += excellon_code
  8031. exported_excellon += footer
  8032. if local_use is None:
  8033. try:
  8034. with open(filename, 'w') as fp:
  8035. fp.write(exported_excellon)
  8036. except PermissionError:
  8037. self.inform.emit('[WARNING] %s' %
  8038. _("Permission denied, saving not possible.\n"
  8039. "Most likely another app is holding the file open and not accessible."))
  8040. return 'fail'
  8041. if self.defaults["global_open_style"] is False:
  8042. self.file_opened.emit("Excellon", filename)
  8043. self.file_saved.emit("Excellon", filename)
  8044. self.inform.emit('[success] %s: %s' %
  8045. (_("Excellon file exported to"), filename))
  8046. else:
  8047. return exported_excellon
  8048. except Exception as e:
  8049. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  8050. return 'fail'
  8051. if use_thread is True:
  8052. with self.proc_container.new(_("Exporting Excellon")) as proc:
  8053. def job_thread_exc(app_obj):
  8054. ret = make_excellon()
  8055. if ret == 'fail':
  8056. self.inform.emit('[ERROR_NOTCL] %s' %
  8057. _('Could not export Excellon file.'))
  8058. return
  8059. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8060. else:
  8061. ret = make_excellon()
  8062. if ret == 'fail':
  8063. self.inform.emit('[ERROR_NOTCL] %s' %
  8064. _('Could not export Excellon file.'))
  8065. return 'fail'
  8066. if local_use is not None:
  8067. return ret
  8068. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  8069. """
  8070. Exports a Gerber Object to an Gerber file.
  8071. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  8072. :param filename: Path to the Gerber file to save to.
  8073. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  8074. When not None, the value will be the actual Gerber object for which to create the Gerber code
  8075. :param use_thread: if to be run in a separate thread
  8076. :return:
  8077. """
  8078. self.report_usage("export_gerber()")
  8079. if filename is None:
  8080. filename = self.defaults["global_last_save_folder"]
  8081. self.log.debug("export_gerber()")
  8082. if local_use is None:
  8083. try:
  8084. obj = self.collection.get_by_name(str(obj_name))
  8085. except:
  8086. # TODO: The return behavior has not been established... should raise exception?
  8087. return "Could not retrieve object: %s" % obj_name
  8088. else:
  8089. obj = local_use
  8090. # updated units
  8091. gunits = self.defaults["gerber_exp_units"]
  8092. gwhole = self.defaults["gerber_exp_integer"]
  8093. gfract = self.defaults["gerber_exp_decimals"]
  8094. gzeros = self.defaults["gerber_exp_zeros"]
  8095. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8096. if fc_units == 'MM':
  8097. factor = 1 if gunits == 'MM' else 0.03937
  8098. else:
  8099. factor = 25.4 if gunits == 'MM' else 1
  8100. def make_gerber():
  8101. try:
  8102. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8103. header = 'G04*\n'
  8104. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  8105. (str(self.version), str(self.version_date))
  8106. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  8107. header += 'G04 Created on : %s*' % time_str + '\n'
  8108. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  8109. header += "%MO{units}*%\n".format(units=gunits)
  8110. for apid in obj.apertures:
  8111. if obj.apertures[apid]['type'] == 'C':
  8112. header += "%ADD{apid}{type},{size}*%\n".format(
  8113. apid=str(apid),
  8114. type='C',
  8115. size=(factor * obj.apertures[apid]['size'])
  8116. )
  8117. elif obj.apertures[apid]['type'] == 'R':
  8118. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8119. apid=str(apid),
  8120. type='R',
  8121. width=(factor * obj.apertures[apid]['width']),
  8122. height=(factor * obj.apertures[apid]['height'])
  8123. )
  8124. elif obj.apertures[apid]['type'] == 'O':
  8125. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8126. apid=str(apid),
  8127. type='O',
  8128. width=(factor * obj.apertures[apid]['width']),
  8129. height=(factor * obj.apertures[apid]['height'])
  8130. )
  8131. header += '\n'
  8132. # obsolete units but some software may need it
  8133. if gunits == 'IN':
  8134. header += 'G70*\n'
  8135. else:
  8136. header += 'G71*\n'
  8137. # Absolute Mode
  8138. header += 'G90*\n'
  8139. header += 'G01*\n'
  8140. # positive polarity
  8141. header += '%LPD*%\n'
  8142. footer = 'M02*\n'
  8143. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  8144. exported_gerber = header
  8145. exported_gerber += gerber_code
  8146. exported_gerber += footer
  8147. if local_use is None:
  8148. try:
  8149. with open(filename, 'w') as fp:
  8150. fp.write(exported_gerber)
  8151. except PermissionError:
  8152. self.inform.emit('[WARNING] %s' %
  8153. _("Permission denied, saving not possible.\n"
  8154. "Most likely another app is holding the file open and not accessible."))
  8155. return 'fail'
  8156. if self.defaults["global_open_style"] is False:
  8157. self.file_opened.emit("Gerber", filename)
  8158. self.file_saved.emit("Gerber", filename)
  8159. self.inform.emit('[success] %s: %s' %
  8160. (_("Gerber file exported to"), filename))
  8161. else:
  8162. return exported_gerber
  8163. except Exception as e:
  8164. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  8165. return 'fail'
  8166. if use_thread is True:
  8167. with self.proc_container.new(_("Exporting Gerber")) as proc:
  8168. def job_thread_grb(app_obj):
  8169. ret = make_gerber()
  8170. if ret == 'fail':
  8171. self.inform.emit('[ERROR_NOTCL] %s' %
  8172. _('Could not export Gerber file.'))
  8173. return
  8174. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  8175. else:
  8176. ret = make_gerber()
  8177. if ret == 'fail':
  8178. self.inform.emit('[ERROR_NOTCL] %s' %
  8179. _('Could not export Gerber file.'))
  8180. return 'fail'
  8181. if local_use is not None:
  8182. return ret
  8183. def export_dxf(self, obj_name, filename, use_thread=True):
  8184. """
  8185. Exports a Geometry Object to an DXF file.
  8186. :param obj_name: the name of the FlatCAM object to be saved as DXF
  8187. :param filename: Path to the DXF file to save to.
  8188. :param use_thread: if to be run in a separate thread
  8189. :return:
  8190. """
  8191. self.report_usage("export_dxf()")
  8192. if filename is None:
  8193. filename = self.defaults["global_last_save_folder"]
  8194. self.log.debug("export_dxf()")
  8195. format_exc = ''
  8196. units = ''
  8197. try:
  8198. obj = self.collection.get_by_name(str(obj_name))
  8199. except:
  8200. # TODO: The return behavior has not been established... should raise exception?
  8201. return "Could not retrieve object: %s" % obj_name
  8202. # updated units
  8203. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8204. if units == 'IN' or units == 'INCH':
  8205. units = 'INCH'
  8206. elif units == 'MM' or units == 'METIRC':
  8207. units ='METRIC'
  8208. def make_dxf():
  8209. try:
  8210. dxf_code = obj.export_dxf()
  8211. dxf_code.saveas(filename)
  8212. if self.defaults["global_open_style"] is False:
  8213. self.file_opened.emit("DXF", filename)
  8214. self.file_saved.emit("DXF", filename)
  8215. self.inform.emit('[success] %s: %s' %
  8216. (_("DXF file exported to"), filename))
  8217. except:
  8218. return 'fail'
  8219. if use_thread is True:
  8220. with self.proc_container.new(_("Exporting DXF")) as proc:
  8221. def job_thread_exc(app_obj):
  8222. ret = make_dxf()
  8223. if ret == 'fail':
  8224. app_obj.inform.emit('[WARNING_NOTCL] %s' %
  8225. _('Could not export DXF file.'))
  8226. return
  8227. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8228. else:
  8229. ret = make_dxf()
  8230. if ret == 'fail':
  8231. self.inform.emit('[WARNING_NOTCL] %s' %
  8232. _('Could not export DXF file.'))
  8233. return
  8234. def import_svg(self, filename, geo_type='geometry', outname=None):
  8235. """
  8236. Adds a new Geometry Object to the projects and populates
  8237. it with shapes extracted from the SVG file.
  8238. :param filename: Path to the SVG file.
  8239. :param outname:
  8240. :return:
  8241. """
  8242. self.report_usage("import_svg()")
  8243. obj_type = ""
  8244. if geo_type is None or geo_type == "geometry":
  8245. obj_type = "geometry"
  8246. elif geo_type == "gerber":
  8247. obj_type = geo_type
  8248. else:
  8249. self.inform.emit('[ERROR_NOTCL] %s' %
  8250. _("Not supported type is picked as parameter. "
  8251. "Only Geometry and Gerber are supported"))
  8252. return
  8253. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8254. def obj_init(geo_obj, app_obj):
  8255. geo_obj.import_svg(filename, obj_type, units=units)
  8256. geo_obj.multigeo = False
  8257. with self.proc_container.new(_("Importing SVG")) as proc:
  8258. # Object name
  8259. name = outname or filename.split('/')[-1].split('\\')[-1]
  8260. self.new_object(obj_type, name, obj_init, autoselected=False)
  8261. self.progress.emit(20)
  8262. # Register recent file
  8263. self.file_opened.emit("svg", filename)
  8264. # GUI feedback
  8265. self.inform.emit('[success] %s: %s' %
  8266. (_("Opened"), filename))
  8267. self.progress.emit(100)
  8268. def import_dxf(self, filename, geo_type='geometry', outname=None):
  8269. """
  8270. Adds a new Geometry Object to the projects and populates
  8271. it with shapes extracted from the DXF file.
  8272. :param filename: Path to the DXF file.
  8273. :param outname:
  8274. :type putname: str
  8275. :return:
  8276. """
  8277. self.report_usage("import_dxf()")
  8278. obj_type = ""
  8279. if geo_type is None or geo_type == "geometry":
  8280. obj_type = "geometry"
  8281. elif geo_type == "gerber":
  8282. obj_type = geo_type
  8283. else:
  8284. self.inform.emit('[ERROR_NOTCL] %s' %
  8285. _("Not supported type is picked as parameter. "
  8286. "Only Geometry and Gerber are supported"))
  8287. return
  8288. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8289. def obj_init(geo_obj, app_obj):
  8290. geo_obj.import_dxf(filename, obj_type, units=units)
  8291. geo_obj.multigeo = False
  8292. with self.proc_container.new(_("Importing DXF")) as proc:
  8293. # Object name
  8294. name = outname or filename.split('/')[-1].split('\\')[-1]
  8295. self.new_object(obj_type, name, obj_init, autoselected=False)
  8296. self.progress.emit(20)
  8297. # Register recent file
  8298. self.file_opened.emit("dxf", filename)
  8299. # GUI feedback
  8300. self.inform.emit('[success] %s: %s' %
  8301. (_("Opened"), filename))
  8302. self.progress.emit(100)
  8303. def import_image(self, filename, o_type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  8304. """
  8305. Adds a new Geometry Object to the projects and populates
  8306. it with shapes extracted from the SVG file.
  8307. :param filename: Path to the SVG file.
  8308. :param o_type: type of FlatCAM objeect
  8309. :param dpi: dot per inch
  8310. :param mode: black or color
  8311. :param mask: dictate the level of detail
  8312. :param outname: name for the resulting file
  8313. :return:
  8314. """
  8315. self.report_usage("import_image()")
  8316. if o_type is None or o_type == "geometry":
  8317. obj_type = "geometry"
  8318. elif o_type == "gerber":
  8319. obj_type = o_type
  8320. else:
  8321. self.inform.emit('[ERROR_NOTCL] %s' %
  8322. _("Not supported type is picked as parameter. "
  8323. "Only Geometry and Gerber are supported"))
  8324. return
  8325. def obj_init(geo_obj, app_obj):
  8326. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  8327. geo_obj.multigeo = False
  8328. with self.proc_container.new(_("Importing Image")) as proc:
  8329. # Object name
  8330. name = outname or filename.split('/')[-1].split('\\')[-1]
  8331. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  8332. self.new_object(obj_type, name, obj_init)
  8333. self.progress.emit(20)
  8334. # Register recent file
  8335. self.file_opened.emit("image", filename)
  8336. # GUI feedback
  8337. self.inform.emit('[success] %s: %s' %
  8338. (_("Opened"), filename))
  8339. self.progress.emit(100)
  8340. def open_gerber(self, filename, outname=None):
  8341. """
  8342. Opens a Gerber file, parses it and creates a new object for
  8343. it in the program. Thread-safe.
  8344. :param outname: Name of the resulting object. None causes the
  8345. name to be that of the file.
  8346. :param filename: Gerber file filename
  8347. :type filename: str
  8348. :param follow: If true, the parser will not create polygons, just lines
  8349. following the gerber path.
  8350. :type follow: bool
  8351. :return: None
  8352. """
  8353. # How the object should be initialized
  8354. def obj_init(gerber_obj, app_obj):
  8355. assert isinstance(gerber_obj, FlatCAMGerber), \
  8356. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  8357. # Opening the file happens here
  8358. self.progress.emit(30)
  8359. try:
  8360. gerber_obj.parse_file(filename)
  8361. except IOError:
  8362. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8363. (_("Failed to open file"), filename))
  8364. app_obj.progress.emit(0)
  8365. return "fail"
  8366. except ParseError as err:
  8367. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' %
  8368. (_("Failed to parse file"), filename, str(err)))
  8369. app_obj.progress.emit(0)
  8370. self.log.error(str(err))
  8371. return "fail"
  8372. except Exception as e:
  8373. log.debug("App.open_gerber() --> %s" % str(e))
  8374. msg = '[ERROR] %s' % \
  8375. _("An internal error has occurred. See shell.\n")
  8376. msg += traceback.format_exc()
  8377. app_obj.inform.emit(msg)
  8378. return "fail"
  8379. if gerber_obj.is_empty():
  8380. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  8381. # self.collection.set_active(gerber_obj.options["name"])
  8382. # self.collection.delete_active()
  8383. self.inform.emit('[ERROR_NOTCL] %s' %
  8384. _("Object is not Gerber file or empty. Aborting object creation."))
  8385. return "fail"
  8386. # Further parsing
  8387. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  8388. App.log.debug("open_gerber()")
  8389. with self.proc_container.new(_("Opening Gerber")) as proc:
  8390. self.progress.emit(10)
  8391. # Object name
  8392. name = outname or filename.split('/')[-1].split('\\')[-1]
  8393. # # ## Object creation # ##
  8394. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  8395. if ret == 'fail':
  8396. self.inform.emit('[ERROR_NOTCL]%s' %
  8397. _(' Open Gerber failed. Probable not a Gerber file.'))
  8398. return
  8399. # Register recent file
  8400. self.file_opened.emit("gerber", filename)
  8401. self.progress.emit(100)
  8402. # GUI feedback
  8403. self.inform.emit('[success] %s: %s' %
  8404. (_("Opened"), filename))
  8405. def open_excellon(self, filename, outname=None, plot=True):
  8406. """
  8407. Opens an Excellon file, parses it and creates a new object for
  8408. it in the program. Thread-safe.
  8409. :param outname: Name of the resulting object. None causes the
  8410. name to be that of the file.
  8411. :param filename: Excellon file filename
  8412. :type filename: str
  8413. :return: None
  8414. """
  8415. App.log.debug("open_excellon()")
  8416. # How the object should be initialized
  8417. def obj_init(excellon_obj, app_obj):
  8418. # self.progress.emit(20)
  8419. try:
  8420. ret = excellon_obj.parse_file(filename=filename)
  8421. if ret == "fail":
  8422. log.debug("Excellon parsing failed.")
  8423. self.inform.emit('[ERROR_NOTCL] %s' %
  8424. _("This is not Excellon file."))
  8425. return "fail"
  8426. except IOError:
  8427. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8428. (_("Cannot open file"), filename))
  8429. log.debug("Could not open Excellon object.")
  8430. self.progress.emit(0) # TODO: self and app_bjj mixed
  8431. return "fail"
  8432. except:
  8433. msg = '[ERROR_NOTCL] %s' % \
  8434. _("An internal error has occurred. See shell.\n")
  8435. msg += traceback.format_exc()
  8436. app_obj.inform.emit(msg)
  8437. return "fail"
  8438. ret = excellon_obj.create_geometry()
  8439. if ret == 'fail':
  8440. log.debug("Could not create geometry for Excellon object.")
  8441. return "fail"
  8442. for tool in excellon_obj.tools:
  8443. if excellon_obj.tools[tool]['solid_geometry']:
  8444. return
  8445. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8446. (_("No geometry found in file"), filename))
  8447. return "fail"
  8448. with self.proc_container.new(_("Opening Excellon.")):
  8449. # Object name
  8450. name = outname or filename.split('/')[-1].split('\\')[-1]
  8451. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8452. if ret_val == 'fail':
  8453. self.inform.emit('[ERROR_NOTCL] %s' %
  8454. _('Open Excellon file failed. Probable not an Excellon file.'))
  8455. return
  8456. # Register recent file
  8457. self.file_opened.emit("excellon", filename)
  8458. # GUI feedback
  8459. self.inform.emit('[success] %s: %s' %
  8460. (_("Opened"), filename))
  8461. def open_gcode(self, filename, outname=None, plot=True):
  8462. """
  8463. Opens a G-gcode file, parses it and creates a new object for
  8464. it in the program. Thread-safe.
  8465. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8466. :param filename: G-code file filename
  8467. :type filename: str
  8468. :return: None
  8469. """
  8470. App.log.debug("open_gcode()")
  8471. # How the object should be initialized
  8472. def obj_init(job_obj, app_obj_):
  8473. """
  8474. :param job_obj: the resulting object
  8475. :type app_obj_: App
  8476. """
  8477. assert isinstance(app_obj_, App), \
  8478. "Initializer expected App, got %s" % type(app_obj_)
  8479. self.progress.emit(10)
  8480. try:
  8481. f = open(filename)
  8482. gcode = f.read()
  8483. f.close()
  8484. except IOError:
  8485. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  8486. (_("Failed to open"), filename))
  8487. self.progress.emit(0)
  8488. return "fail"
  8489. job_obj.gcode = gcode
  8490. self.progress.emit(20)
  8491. ret = job_obj.gcode_parse()
  8492. if ret == "fail":
  8493. self.inform.emit('[ERROR_NOTCL] %s' %
  8494. _("This is not GCODE"))
  8495. return "fail"
  8496. self.progress.emit(60)
  8497. job_obj.create_geometry()
  8498. with self.proc_container.new(_("Opening G-Code.")):
  8499. # Object name
  8500. name = outname or filename.split('/')[-1].split('\\')[-1]
  8501. # New object creation and file processing
  8502. ret = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8503. if ret == 'fail':
  8504. self.inform.emit('[ERROR_NOTCL] %s' %
  8505. _("Failed to create CNCJob Object. Probable not a GCode file.\n "
  8506. "Attempting to create a FlatCAM CNCJob Object from "
  8507. "G-Code file failed during processing"))
  8508. return "fail"
  8509. # Register recent file
  8510. self.file_opened.emit("cncjob", filename)
  8511. # GUI feedback
  8512. self.inform.emit('[success] %s: %s' %
  8513. (_("Opened"), filename))
  8514. self.progress.emit(100)
  8515. def open_config_file(self, filename, run_from_arg=None):
  8516. """
  8517. Loads a config file from the specified file.
  8518. :param filename: Name of the file from which to load.
  8519. :type filename: str
  8520. :return: None
  8521. """
  8522. App.log.debug("Opening config file: " + filename)
  8523. if run_from_arg:
  8524. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8525. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8526. _("Opening FlatCAM Config file.")),
  8527. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8528. color=QtGui.QColor("gray"))
  8529. # add the tab if it was closed
  8530. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _("Code Editor"))
  8531. # first clear previous text in text editor (if any)
  8532. self.ui.code_editor.clear()
  8533. # Switch plot_area to CNCJob tab
  8534. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  8535. try:
  8536. if filename:
  8537. f = QtCore.QFile(filename)
  8538. if f.open(QtCore.QIODevice.ReadOnly):
  8539. stream = QtCore.QTextStream(f)
  8540. gcode_edited = stream.readAll()
  8541. self.ui.code_editor.setPlainText(gcode_edited)
  8542. f.close()
  8543. except IOError:
  8544. App.log.error("Failed to open config file: %s" % filename)
  8545. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8546. (_("Failed to open config file"), filename))
  8547. return
  8548. def open_project(self, filename, run_from_arg=None, plot=True, cli=None):
  8549. """
  8550. Loads a project from the specified file.
  8551. 1) Loads and parses file
  8552. 2) Registers the file as recently opened.
  8553. 3) Calls on_file_new()
  8554. 4) Updates options
  8555. 5) Calls new_object() with the object's from_dict() as init method.
  8556. 6) Calls plot_all() if plot=True
  8557. :param filename: Name of the file from which to load.
  8558. :type filename: str
  8559. :param run_from_arg: True if run for arguments
  8560. :param plot: If True plot all objects in the project
  8561. :param cli: run from command line
  8562. :return: None
  8563. """
  8564. App.log.debug("Opening project: " + filename)
  8565. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8566. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8567. if cli is None:
  8568. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  8569. if run_from_arg:
  8570. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8571. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8572. _("Opening FlatCAM Project file.")),
  8573. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8574. color=QtGui.QColor("gray"))
  8575. # Open and parse an uncompressed Project file
  8576. try:
  8577. f = open(filename, 'r')
  8578. except IOError:
  8579. App.log.error("Failed to open project file: %s" % filename)
  8580. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8581. (_("Failed to open project file"), filename))
  8582. return
  8583. try:
  8584. d = json.load(f, object_hook=dict2obj)
  8585. except Exception as e:
  8586. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  8587. (filename, str(e)))
  8588. f.close()
  8589. # Open and parse a compressed Project file
  8590. try:
  8591. with lzma.open(filename) as f:
  8592. file_content = f.read().decode('utf-8')
  8593. d = json.loads(file_content, object_hook=dict2obj)
  8594. except Exception as e:
  8595. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8596. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8597. (_("Failed to open project file"), filename))
  8598. return
  8599. # Clear the current project
  8600. # # NOT THREAD SAFE # ##
  8601. if run_from_arg is True:
  8602. pass
  8603. elif cli is True:
  8604. self.delete_selection_shape()
  8605. else:
  8606. self.on_file_new()
  8607. # Project options
  8608. self.options.update(d['options'])
  8609. self.project_filename = filename
  8610. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8611. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8612. if cli is None:
  8613. self.set_screen_units(self.options["units"])
  8614. # Re create objects
  8615. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  8616. for obj in d['objs']:
  8617. def obj_init(obj_inst, app_inst):
  8618. obj_inst.from_dict(obj)
  8619. App.log.debug("Recreating from opened project an %s object: %s" %
  8620. (obj['kind'].capitalize(), obj['options']['name']))
  8621. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8622. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8623. if cli is None:
  8624. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  8625. obj['kind'].upper(),
  8626. obj['options']['name']
  8627. )
  8628. )
  8629. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  8630. self.inform.emit('[success] %s: %s' %
  8631. (_("Project loaded from"), filename))
  8632. self.should_we_save = False
  8633. self.file_opened.emit("project", filename)
  8634. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8635. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8636. if cli is None:
  8637. self.set_ui_title(name=self.project_filename)
  8638. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  8639. def propagate_defaults(self, silent=False):
  8640. """
  8641. This method is used to set default values in classes. It's
  8642. an alternative to project options but allows the use
  8643. of values invisible to the user.
  8644. :return: None
  8645. """
  8646. if silent is False:
  8647. self.log.debug("propagate_defaults()")
  8648. # Which objects to update the given parameters.
  8649. routes = {
  8650. "global_zdownrate": CNCjob,
  8651. "excellon_zeros": Excellon,
  8652. "excellon_format_upper_in": Excellon,
  8653. "excellon_format_lower_in": Excellon,
  8654. "excellon_format_upper_mm": Excellon,
  8655. "excellon_format_lower_mm": Excellon,
  8656. "excellon_units": Excellon,
  8657. "gerber_use_buffer_for_union": Gerber,
  8658. "geometry_multidepth": Geometry
  8659. }
  8660. for param in routes:
  8661. if param in routes[param].defaults:
  8662. try:
  8663. routes[param].defaults[param] = self.defaults[param]
  8664. if silent is False:
  8665. self.log.debug(" " + param + " OK")
  8666. except KeyError:
  8667. if silent is False:
  8668. self.log.debug(" ERROR: " + param + " not in defaults.")
  8669. else:
  8670. # Try extracting the name:
  8671. # classname_param here is param in the object
  8672. if param.find(routes[param].__name__.lower() + "_") == 0:
  8673. p = param[len(routes[param].__name__) + 1:]
  8674. if p in routes[param].defaults:
  8675. routes[param].defaults[p] = self.defaults[param]
  8676. if silent is False:
  8677. self.log.debug(" " + param + " OK!")
  8678. def restore_main_win_geom(self):
  8679. try:
  8680. self.ui.setGeometry(self.defaults["global_def_win_x"],
  8681. self.defaults["global_def_win_y"],
  8682. self.defaults["global_def_win_w"],
  8683. self.defaults["global_def_win_h"])
  8684. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  8685. except KeyError as e:
  8686. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  8687. def plot_all(self, zoom=True):
  8688. """
  8689. Re-generates all plots from all objects.
  8690. :return: None
  8691. """
  8692. self.log.debug("Plot_all()")
  8693. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  8694. for obj in self.collection.get_list():
  8695. def worker_task(obj):
  8696. with self.proc_container.new("Plotting"):
  8697. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  8698. if zoom:
  8699. self.object_plotted.emit(obj)
  8700. # Send to worker
  8701. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  8702. def register_folder(self, filename):
  8703. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  8704. def register_save_folder(self, filename):
  8705. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  8706. def set_progress_bar(self, percentage, text=""):
  8707. self.ui.progress_bar.setValue(int(percentage))
  8708. def setup_shell(self):
  8709. """
  8710. Creates shell functions. Runs once at startup.
  8711. :return: None
  8712. """
  8713. self.log.debug("setup_shell()")
  8714. def shelp(p=None):
  8715. if not p:
  8716. return _("Available commands:\n") + \
  8717. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  8718. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  8719. if p not in commands:
  8720. return "Unknown command: %s" % p
  8721. return commands[p]["help"]
  8722. # --- Migrated to new architecture ---
  8723. # def options(name):
  8724. # ops = self.collection.get_by_name(str(name)).options
  8725. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  8726. def h(*args):
  8727. """
  8728. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  8729. and standalone parameters into list.
  8730. """
  8731. kwa = {}
  8732. a = []
  8733. n = len(args)
  8734. name = None
  8735. for i in range(n):
  8736. match = re.search(r'^-([a-zA-Z].*)', args[i])
  8737. if match:
  8738. assert name is None
  8739. name = match.group(1)
  8740. continue
  8741. if name is None:
  8742. a.append(args[i])
  8743. else:
  8744. kwa[name] = args[i]
  8745. name = None
  8746. return a, kwa
  8747. @contextmanager
  8748. def wait_signal(signal, timeout=10000):
  8749. """
  8750. Block loop until signal emitted, timeout (ms) elapses
  8751. or unhandled exception happens in a thread.
  8752. :param timeout: time after which the loop is exited
  8753. :param signal: Signal to wait for.
  8754. """
  8755. loop = QtCore.QEventLoop()
  8756. # Normal termination
  8757. signal.connect(loop.quit)
  8758. # Termination by exception in thread
  8759. self.thread_exception.connect(loop.quit)
  8760. status = {'timed_out': False}
  8761. def report_quit():
  8762. status['timed_out'] = True
  8763. loop.quit()
  8764. yield
  8765. # Temporarily change how exceptions are managed.
  8766. oeh = sys.excepthook
  8767. ex = []
  8768. def except_hook(type_, value, traceback_):
  8769. ex.append(value)
  8770. oeh(type_, value, traceback_)
  8771. sys.excepthook = except_hook
  8772. # Terminate on timeout
  8773. if timeout is not None:
  8774. QtCore.QTimer.singleShot(timeout, report_quit)
  8775. # # ## Block ## ##
  8776. loop.exec_()
  8777. # Restore exception management
  8778. sys.excepthook = oeh
  8779. if ex:
  8780. self.raiseTclError(str(ex[0]))
  8781. if status['timed_out']:
  8782. raise Exception('Timed out!')
  8783. def make_docs():
  8784. output = ''
  8785. import collections
  8786. od = collections.OrderedDict(sorted(commands.items()))
  8787. for cmd_, val in od.items():
  8788. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  8789. t = val['help']
  8790. usage_i = t.find('>')
  8791. if usage_i < 0:
  8792. expl = t
  8793. output += expl + '\n\n'
  8794. continue
  8795. expl = t[:usage_i - 1]
  8796. output += expl + '\n\n'
  8797. end_usage_i = t[usage_i:].find('\n')
  8798. if end_usage_i < 0:
  8799. end_usage_i = len(t[usage_i:])
  8800. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  8801. else:
  8802. extras = t[usage_i+end_usage_i+1:]
  8803. parts = [s.strip() for s in extras.split('\n')]
  8804. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  8805. for p in parts:
  8806. output += ' ' + p + '\n\n'
  8807. return output
  8808. '''
  8809. Howto implement TCL shell commands:
  8810. All parameters passed to command should be possible to set as None and test it afterwards.
  8811. This is because we need to see error caused in tcl,
  8812. if None value as default parameter is not allowed TCL will return empty error.
  8813. Use:
  8814. def mycommand(name=None,...):
  8815. Test it like this:
  8816. if name is None:
  8817. self.raise_tcl_error('Argument name is missing.')
  8818. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  8819. otherwise we will miss it and processing will silently continue.
  8820. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  8821. which is catched in exec_command and displayed in TCL shell console with red background.
  8822. Error in console is displayed with TCL trace.
  8823. This behavior works only within main thread,
  8824. errors with promissed tasks can be catched and detected only with log.
  8825. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  8826. TCL shell.
  8827. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  8828. '''
  8829. commands = {
  8830. 'help': {
  8831. 'fcn': shelp,
  8832. 'help': _("Shows list of commands.")
  8833. },
  8834. }
  8835. # Import/overwrite tcl commands as objects of TclCommand descendants
  8836. # This modifies the variable 'commands'.
  8837. tclCommands.register_all_commands(self, commands)
  8838. # Add commands to the tcl interpreter
  8839. for cmd in commands:
  8840. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  8841. # Make the tcl puts function return instead of print to stdout
  8842. self.tcl.eval('''
  8843. rename puts original_puts
  8844. proc puts {args} {
  8845. if {[llength $args] == 1} {
  8846. return "[lindex $args 0]"
  8847. } else {
  8848. eval original_puts $args
  8849. }
  8850. }
  8851. ''')
  8852. def setup_recent_items(self):
  8853. # TODO: Move this to constructor
  8854. icons = {
  8855. "gerber": "share/flatcam_icon16.png",
  8856. "excellon": "share/drill16.png",
  8857. 'geometry': "share/geometry16.png",
  8858. "cncjob": "share/cnc16.png",
  8859. "project": "share/project16.png",
  8860. "svg": "share/geometry16.png",
  8861. "dxf": "share/dxf16.png",
  8862. "pdf": "share/pdf32.png",
  8863. "image": "share/image16.png"
  8864. }
  8865. openers = {
  8866. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  8867. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  8868. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  8869. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  8870. 'project': self.open_project,
  8871. 'svg': self.import_svg,
  8872. 'dxf': self.import_dxf,
  8873. 'image': self.import_image,
  8874. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  8875. }
  8876. # Open recent file for files
  8877. try:
  8878. f = open(self.data_path + '/recent.json')
  8879. except IOError:
  8880. App.log.error("Failed to load recent item list.")
  8881. self.inform.emit('[ERROR_NOTCL] %s' %
  8882. _("Failed to load recent item list."))
  8883. return
  8884. try:
  8885. self.recent = json.load(f)
  8886. except json.scanner.JSONDecodeError:
  8887. App.log.error("Failed to parse recent item list.")
  8888. self.inform.emit('[ERROR_NOTCL] %s' %
  8889. _("Failed to parse recent item list."))
  8890. f.close()
  8891. return
  8892. f.close()
  8893. # Open recent file for projects
  8894. try:
  8895. fp = open(self.data_path + '/recent_projects.json')
  8896. except IOError:
  8897. App.log.error("Failed to load recent project item list.")
  8898. self.inform.emit('[ERROR_NOTCL] %s' %
  8899. _("Failed to load recent projects item list."))
  8900. return
  8901. try:
  8902. self.recent_projects = json.load(fp)
  8903. except json.scanner.JSONDecodeError:
  8904. App.log.error("Failed to parse recent project item list.")
  8905. self.inform.emit('[ERROR_NOTCL] %s' %
  8906. _("Failed to parse recent project item list."))
  8907. fp.close()
  8908. return
  8909. fp.close()
  8910. # Closure needed to create callbacks in a loop.
  8911. # Otherwise late binding occurs.
  8912. def make_callback(func, fname):
  8913. def opener():
  8914. func(fname)
  8915. return opener
  8916. def reset_recent_files():
  8917. # Reset menu
  8918. self.ui.recent.clear()
  8919. self.recent = []
  8920. try:
  8921. f = open(self.data_path + '/recent.json', 'w')
  8922. except IOError:
  8923. App.log.error("Failed to open recent items file for writing.")
  8924. return
  8925. json.dump(self.recent, f)
  8926. def reset_recent_projects():
  8927. # Reset menu
  8928. self.ui.recent_projects.clear()
  8929. self.recent_projects = []
  8930. try:
  8931. fp = open(self.data_path + '/recent_projects.json', 'w')
  8932. except IOError:
  8933. App.log.error("Failed to open recent projects items file for writing.")
  8934. return
  8935. json.dump(self.recent, fp)
  8936. # Reset menu
  8937. self.ui.recent.clear()
  8938. self.ui.recent_projects.clear()
  8939. # Create menu items for projects
  8940. for recent in self.recent_projects:
  8941. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8942. if recent['kind'] == 'project':
  8943. try:
  8944. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8945. # Attach callback
  8946. o = make_callback(openers[recent["kind"]], recent['filename'])
  8947. action.triggered.connect(o)
  8948. self.ui.recent_projects.addAction(action)
  8949. except KeyError:
  8950. App.log.error("Unsupported file type: %s" % recent["kind"])
  8951. # Last action in Recent Files menu is one that Clear the content
  8952. clear_action_proj = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  8953. clear_action_proj.triggered.connect(reset_recent_projects)
  8954. self.ui.recent_projects.addSeparator()
  8955. self.ui.recent_projects.addAction(clear_action_proj)
  8956. # Create menu items for files
  8957. for recent in self.recent:
  8958. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8959. if recent['kind'] != 'project':
  8960. try:
  8961. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8962. # Attach callback
  8963. o = make_callback(openers[recent["kind"]], recent['filename'])
  8964. action.triggered.connect(o)
  8965. self.ui.recent.addAction(action)
  8966. except KeyError:
  8967. App.log.error("Unsupported file type: %s" % recent["kind"])
  8968. # Last action in Recent Files menu is one that Clear the content
  8969. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  8970. clear_action.triggered.connect(reset_recent_files)
  8971. self.ui.recent.addSeparator()
  8972. self.ui.recent.addAction(clear_action)
  8973. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  8974. # self.ui.menufilerecent.set_submenu(recent_menu)
  8975. # recent_menu.show_all()
  8976. # self.ui.recent.show()
  8977. self.log.debug("Recent items list has been populated.")
  8978. def setup_component_editor(self):
  8979. # label = QtWidgets.QLabel("Choose an item from Project")
  8980. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  8981. sel_title = QtWidgets.QTextEdit(
  8982. _('<b>Shortcut Key List</b>'))
  8983. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  8984. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  8985. settings = QSettings("Open Source", "FlatCAM")
  8986. if settings.contains("notebook_font_size"):
  8987. fsize = settings.value('notebook_font_size', type=int)
  8988. else:
  8989. fsize = 12
  8990. tsize = fsize + int(fsize / 2)
  8991. # selected_text = (_('''
  8992. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  8993. #
  8994. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  8995. # The normal flow when working in FlatCAM is the following:</span></p>
  8996. #
  8997. # <ol>
  8998. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into
  8999. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  9000. # even dragging and dropping the files on the GUI.<br />
  9001. # <br />
  9002. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the
  9003. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  9004. # &nbsp;</li>
  9005. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then
  9006. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  9007. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  9008. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  9009. # <br />
  9010. # If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong>
  9011. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  9012. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  9013. # it even if it was out of focus.<br />
  9014. # <br />
  9015. # You can change the parameters in this screen and the flow direction is like this:<br />
  9016. # <br />
  9017. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object
  9018. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  9019. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  9020. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  9021. # </ol>
  9022. #
  9023. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  9024. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  9025. # <strong>F3</strong>.</span></p>
  9026. #
  9027. # ''').format(fsize=fsize, tsize=tsize))
  9028. selected_text = '''
  9029. <p><span style="font-size:{tsize}px"><strong>%s</strong></span></p>
  9030. <p><span style="font-size:{fsize}px"><strong>%s</strong>:<br />
  9031. %s:</span></p>
  9032. <ol>
  9033. <li><span style="font-size:{fsize}px">%s menu&#39;s, %s.<br />
  9034. <br />
  9035. %s &amp; %s.</span><br />
  9036. &nbsp;</li>
  9037. <li><span style="font-size:{fsize}px">%s <strong>%s</strong> (%s), <strong>%s</strong> %s it-s %s.<br />
  9038. <br />
  9039. %s <strong>%s</strong> %s <strong>%s</strong> %s.<br />
  9040. <br />
  9041. %s:<br />
  9042. <br />
  9043. <strong>%s</strong> -&gt; %s -&gt; %s -&gt;<strong> %s </strong> -&gt; %s -&gt; %s -&gt;<strong> %s
  9044. </strong>-&gt; %s <strong>%s)&nbsp;</strong>-&gt; %s</span></li>
  9045. </ol>
  9046. <p><span style="font-size:{fsize}px">%s <strong>%s -&gt; %s</strong>&nbsp;%s it&#39;s %s:
  9047. <strong>F3</strong>.</span></p>
  9048. ''' % (
  9049. _("Selected Tab - Choose an Item from Project Tab"), _("Details"),
  9050. _("The normal flow when working in FlatCAM is the following"),
  9051. _("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM using either the"),
  9052. _("toolbars, key shortcuts or even dragging and dropping the files on the GUI"),
  9053. _("You can also load a FlatCAM project by double clicking on the project file, drag"),
  9054. _("drop of the file into the FLATCAM GUI or through the menu/toolbar links offered within the app"),
  9055. _("Once an object is available in the Project Tab, by selecting it and then focusing on"),
  9056. _("SELECTED TAB"), _("more simpler is to double click the object name in the Project Tab"),
  9057. _("SELECTED TAB"), _("will be updated with the object properties according to"),
  9058. _("kind: Gerber, Excellon, Geometry or CNCJob object"),
  9059. _("If the selection of the object is done on the canvas by single click instead, and the"),
  9060. _("SELECTED TAB"),
  9061. _("is in focus, again the object properties will be displayed into the Selected Tab. Alternatively, "
  9062. "double clicking on the object on the canvas will bring the"),
  9063. _("SELECTED TAB"), _("and populate it even if it was out of focus"),
  9064. _("You can change the parameters in this screen and the flow direction is like this"),
  9065. _("Gerber/Excellon Object"), _("Change Parameter"), _("Generate Geometry"), _("Geometry Object"),
  9066. _("Add tools (change param in Selected Tab)"), _("Generate CNCJob"), _("CNCJob Object"),
  9067. _("Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in"), _("SELECTED TAB"),
  9068. _("Save GCode"), _("A list of key shortcuts is available through an menu entry in"), _("Help"),
  9069. _("Shortcuts List"), _("or through"), _("own key shortcut"),
  9070. )
  9071. sel_title.setText(selected_text)
  9072. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  9073. self.ui.selected_scroll_area.setWidget(sel_title)
  9074. def setup_obj_classes(self):
  9075. """
  9076. Sets up application specifics on the FlatCAMObj class.
  9077. :return: None
  9078. """
  9079. FlatCAMObj.app = self
  9080. ObjectCollection.app = self
  9081. Gerber.app = self
  9082. Excellon.app = self
  9083. Geometry.app = self
  9084. CNCjob.app = self
  9085. FCProcess.app = self
  9086. FCProcessContainer.app = self
  9087. def version_check(self):
  9088. """
  9089. Checks for the latest version of the program. Alerts the
  9090. user if theirs is outdated. This method is meant to be run
  9091. in a separate thread.
  9092. :return: None
  9093. """
  9094. self.log.debug("version_check()")
  9095. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  9096. full_url = App.version_url + \
  9097. "?s=" + str(self.defaults['global_serial']) + \
  9098. "&v=" + str(self.version) + \
  9099. "&os=" + str(self.os) + \
  9100. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  9101. else:
  9102. # no_stats dict; just so it won't break things on website
  9103. no_ststs_dict = {}
  9104. no_ststs_dict["global_ststs"] = {}
  9105. full_url = App.version_url + \
  9106. "?s=" + str(self.defaults['global_serial']) + \
  9107. "&v=" + str(self.version) + \
  9108. "&os=" + str(self.os) + \
  9109. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  9110. App.log.debug("Checking for updates @ %s" % full_url)
  9111. # ## Get the data
  9112. try:
  9113. f = urllib.request.urlopen(full_url)
  9114. except:
  9115. # App.log.warning("Failed checking for latest version. Could not connect.")
  9116. self.log.warning("Failed checking for latest version. Could not connect.")
  9117. self.inform.emit('[WARNING_NOTCL] %s' %
  9118. _("Failed checking for latest version. Could not connect."))
  9119. return
  9120. try:
  9121. data = json.load(f)
  9122. except Exception as e:
  9123. App.log.error("Could not parse information about latest version.")
  9124. self.inform.emit('[ERROR_NOTCL] %s' %
  9125. _("Could not parse information about latest version."))
  9126. App.log.debug("json.load(): %s" % str(e))
  9127. f.close()
  9128. return
  9129. f.close()
  9130. # ## Latest version?
  9131. if self.version >= data["version"]:
  9132. App.log.debug("FlatCAM is up to date!")
  9133. self.inform.emit('[success] %s' %
  9134. _("FlatCAM is up to date!"))
  9135. return
  9136. App.log.debug("Newer version available.")
  9137. self.message.emit(
  9138. _("Newer Version Available"),
  9139. _("There is a newer version of FlatCAM available for download:\n\n") +
  9140. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  9141. _("info")
  9142. )
  9143. def on_plotcanvas_setup(self, container=None):
  9144. """
  9145. This is doing the setup for the plot area (VisPy canvas)
  9146. :param container: widget where to install the canvas
  9147. :return: None
  9148. """
  9149. if container:
  9150. plot_container = container
  9151. else:
  9152. plot_container = self.ui.right_layout
  9153. if self.is_legacy is False:
  9154. self.plotcanvas = PlotCanvas(plot_container, self)
  9155. else:
  9156. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  9157. # So it can receive key presses
  9158. self.plotcanvas.native.setFocus()
  9159. self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  9160. self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  9161. self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  9162. self.plotcanvas.graph_event_connect('mouse_double_click', self.on_double_click_over_plot)
  9163. # Keys over plot enabled
  9164. self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  9165. self.app_cursor = self.plotcanvas.new_cursor()
  9166. if self.ui.grid_snap_btn.isChecked():
  9167. self.app_cursor.enabled = True
  9168. else:
  9169. self.app_cursor.enabled = False
  9170. if self.is_legacy is False:
  9171. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  9172. else:
  9173. # will use the default Matplotlib axes
  9174. self.hover_shapes = ShapeCollectionLegacy()
  9175. def on_zoom_fit(self, event):
  9176. """
  9177. Callback for zoom-out request. This can be either from the corresponding
  9178. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  9179. with axes limits from the geometry bounds of all objects.
  9180. :param event: Ignored.
  9181. :return: None
  9182. """
  9183. self.plotcanvas.fit_view()
  9184. def on_zoom_in(self):
  9185. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  9186. def on_zoom_out(self):
  9187. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  9188. def disable_all_plots(self):
  9189. self.report_usage("disable_all_plots()")
  9190. self.disable_plots(self.collection.get_list())
  9191. self.inform.emit('[success] %s' %
  9192. _("All plots disabled."))
  9193. def disable_other_plots(self):
  9194. self.report_usage("disable_other_plots()")
  9195. self.disable_plots(self.collection.get_non_selected())
  9196. self.inform.emit('[success] %s' %
  9197. _("All non selected plots disabled."))
  9198. def enable_all_plots(self):
  9199. self.report_usage("enable_all_plots()")
  9200. self.enable_plots(self.collection.get_list())
  9201. self.inform.emit('[success] %s' %
  9202. _("All plots enabled."))
  9203. def on_enable_sel_plots(self):
  9204. log.debug("App.on_enable_sel_plot()")
  9205. object_list = self.collection.get_selected()
  9206. self.enable_plots(objects=object_list)
  9207. self.inform.emit('[success] %s' %
  9208. _("Selected plots enabled..."))
  9209. def on_disable_sel_plots(self):
  9210. log.debug("App.on_disable_sel_plot()")
  9211. # self.inform.emit(_("Disabling plots ..."))
  9212. object_list = self.collection.get_selected()
  9213. self.disable_plots(objects=object_list)
  9214. self.inform.emit('[success] %s' %
  9215. _("Selected plots disabled..."))
  9216. def enable_plots(self, objects):
  9217. """
  9218. Disables plots
  9219. :param objects: list of Objects to be enabled
  9220. :return:
  9221. """
  9222. log.debug("Enabling plots ...")
  9223. # self.inform.emit(_("Working ..."))
  9224. for obj in objects:
  9225. if obj.options['plot'] is False:
  9226. obj.options.set_change_callback(lambda x: None)
  9227. obj.options['plot'] = True
  9228. obj.options.set_change_callback(obj.on_options_change)
  9229. def worker_task(objects):
  9230. with self.proc_container.new(_("Enabling plots ...")):
  9231. for obj in objects:
  9232. # obj.options['plot'] = True
  9233. if isinstance(obj, FlatCAMCNCjob):
  9234. obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  9235. else:
  9236. obj.plot(visible=True)
  9237. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9238. # self.plots_updated.emit()
  9239. def disable_plots(self, objects):
  9240. """
  9241. Disables plots
  9242. :param objects: list of Objects to be disabled
  9243. :return:
  9244. """
  9245. # if no objects selected then do nothing
  9246. if not self.collection.get_selected():
  9247. return
  9248. log.debug("Disabling plots ...")
  9249. # self.inform.emit(_("Working ..."))
  9250. for obj in objects:
  9251. if obj.options['plot'] is True:
  9252. obj.options.set_change_callback(lambda x: None)
  9253. obj.options['plot'] = False
  9254. obj.options.set_change_callback(obj.on_options_change)
  9255. try:
  9256. self.delete_selection_shape()
  9257. except Exception as e:
  9258. log.debug("App.disable_plots() --> %s" % str(e))
  9259. # self.plots_updated.emit()
  9260. def worker_task(objects):
  9261. with self.proc_container.new(_("Disabling plots ...")):
  9262. for obj in objects:
  9263. # obj.options['plot'] = True
  9264. if isinstance(obj, FlatCAMCNCjob):
  9265. obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  9266. else:
  9267. obj.plot(visible=False)
  9268. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9269. def toggle_plots(self, objects):
  9270. """
  9271. Toggle plots visibility
  9272. :param objects: list of Objects for which to be toggled the visibility
  9273. :return:
  9274. """
  9275. # if no objects selected then do nothing
  9276. if not self.collection.get_selected():
  9277. return
  9278. log.debug("Toggling plots ...")
  9279. self.inform.emit(_("Working ..."))
  9280. for obj in objects:
  9281. if obj.options['plot'] is False:
  9282. obj.options['plot'] = True
  9283. else:
  9284. obj.options['plot'] = False
  9285. self.plots_updated.emit()
  9286. def clear_plots(self):
  9287. objects = self.collection.get_list()
  9288. for obj in objects:
  9289. obj.clear(obj == objects[-1])
  9290. # Clear pool to free memory
  9291. self.clear_pool()
  9292. def generate_cnc_job(self, objects):
  9293. self.report_usage("generate_cnc_job()")
  9294. # for obj in objects:
  9295. # obj.generatecncjob()
  9296. for obj in objects:
  9297. obj.on_generatecnc_button_click()
  9298. def save_project(self, filename, quit_action=False, silent=False):
  9299. """
  9300. Saves the current project to the specified file.
  9301. :param filename: Name of the file in which to save.
  9302. :type filename: str
  9303. :param quit_action: if the project saving will be followed by an app quit; boolean
  9304. :param silent: if True will not display status messages
  9305. :return: None
  9306. """
  9307. self.log.debug("save_project()")
  9308. self.save_in_progress = True
  9309. with self.proc_container.new(_("Saving FlatCAM Project")):
  9310. # Capture the latest changes
  9311. # Current object
  9312. try:
  9313. self.collection.get_active().read_form()
  9314. except:
  9315. self.log.debug("There was no active object")
  9316. pass
  9317. # Project options
  9318. self.options_read_form()
  9319. # Serialize the whole project
  9320. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  9321. "options": self.options,
  9322. "version": self.version}
  9323. if self.defaults["global_save_compressed"] is True:
  9324. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  9325. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  9326. # # Write
  9327. f.write(g)
  9328. self.inform.emit('[success] %s: %s' %
  9329. (_("Project saved to"), filename))
  9330. else:
  9331. # Open file
  9332. try:
  9333. f = open(filename, 'w')
  9334. except IOError:
  9335. App.log.error("Failed to open file for saving: %s", filename)
  9336. return
  9337. # Write
  9338. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  9339. f.close()
  9340. # verification of the saved project
  9341. # Open and parse
  9342. try:
  9343. saved_f = open(filename, 'r')
  9344. except IOError:
  9345. if silent is False:
  9346. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9347. (_("Failed to verify project file"), filename, _("Retry to save it."))
  9348. )
  9349. return
  9350. try:
  9351. saved_d = json.load(saved_f, object_hook=dict2obj)
  9352. except:
  9353. if silent is False:
  9354. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9355. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9356. )
  9357. f.close()
  9358. return
  9359. saved_f.close()
  9360. if silent is False:
  9361. if 'version' in saved_d:
  9362. self.inform.emit('[success] %s: %s' %
  9363. (_("Project saved to"), filename))
  9364. else:
  9365. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9366. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9367. )
  9368. settings = QSettings("Open Source", "FlatCAM")
  9369. lock_state = self.ui.lock_action.isChecked()
  9370. settings.setValue('toolbar_lock', lock_state)
  9371. # This will write the setting to the platform specific storage.
  9372. del settings
  9373. # if quit:
  9374. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  9375. # t.start()
  9376. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  9377. def start_delayed_quit(self, delay, filename, should_quit=None):
  9378. """
  9379. :param delay: period of checking if project file size is more than zero; in seconds
  9380. :param filename: the name of the project file to be checked periodically for size more than zero
  9381. :param should_quit: if the task finished will be followed by an app quit; boolean
  9382. :return:
  9383. """
  9384. to_quit = should_quit
  9385. self.save_timer = QtCore.QTimer()
  9386. self.save_timer.setInterval(delay)
  9387. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  9388. self.save_timer.start()
  9389. def check_project_file_size(self, filename, should_quit=None):
  9390. """
  9391. :param filename: the name of the project file to be checked periodically for size more than zero
  9392. :param should_quit: will quit the app if True; boolean
  9393. :return:
  9394. """
  9395. try:
  9396. if os.stat(filename).st_size > 0:
  9397. self.save_in_progress = False
  9398. self.save_timer.stop()
  9399. if should_quit:
  9400. self.app_quit.emit()
  9401. except Exception as e:
  9402. traceback.print_exc()
  9403. def on_options_app2project(self):
  9404. """
  9405. Callback for Options->Transfer Options->App=>Project. Copies options
  9406. from application defaults to project defaults.
  9407. :return: None
  9408. """
  9409. self.report_usage("on_options_app2project")
  9410. self.defaults_read_form()
  9411. self.options.update(self.defaults)
  9412. self.options_write_form()
  9413. def on_options_project2app(self):
  9414. """
  9415. Callback for Options->Transfer Options->Project=>App. Copies options
  9416. from project defaults to application defaults.
  9417. :return: None
  9418. """
  9419. self.report_usage("on_options_project2app")
  9420. self.options_read_form()
  9421. self.defaults.update(self.options)
  9422. self.defaults_write_form()
  9423. def on_options_project2object(self):
  9424. """
  9425. Callback for Options->Transfer Options->Project=>Object. Copies options
  9426. from project defaults to the currently selected object.
  9427. :return: None
  9428. """
  9429. self.report_usage("on_options_project2object")
  9430. self.options_read_form()
  9431. obj = self.collection.get_active()
  9432. if obj is None:
  9433. self.inform.emit('[WARNING_NOTCL] %s' %
  9434. _("No object selected."))
  9435. return
  9436. for option in self.options:
  9437. if option.find(obj.kind + "_") == 0:
  9438. oname = option[len(obj.kind) + 1:]
  9439. obj.options[oname] = self.options[option]
  9440. obj.to_form() # Update UI
  9441. def on_options_object2project(self):
  9442. """
  9443. Callback for Options->Transfer Options->Object=>Project. Copies options
  9444. from the currently selected object to project defaults.
  9445. :return: None
  9446. """
  9447. self.report_usage("on_options_object2project")
  9448. obj = self.collection.get_active()
  9449. if obj is None:
  9450. self.inform.emit('[WARNING_NOTCL] %s' %
  9451. _("No object selected."))
  9452. return
  9453. obj.read_form()
  9454. for option in obj.options:
  9455. if option in ['name']: # TODO: Handle this better...
  9456. continue
  9457. self.options[obj.kind + "_" + option] = obj.options[option]
  9458. self.options_write_form()
  9459. def on_options_object2app(self):
  9460. """
  9461. Callback for Options->Transfer Options->Object=>App. Copies options
  9462. from the currently selected object to application defaults.
  9463. :return: None
  9464. """
  9465. self.report_usage("on_options_object2app")
  9466. obj = self.collection.get_active()
  9467. if obj is None:
  9468. self.inform.emit('[WARNING_NOTCL] %s' %
  9469. _("No object selected."))
  9470. return
  9471. obj.read_form()
  9472. for option in obj.options:
  9473. if option in ['name']: # TODO: Handle this better...
  9474. continue
  9475. self.defaults[obj.kind + "_" + option] = obj.options[option]
  9476. self.defaults_write_form()
  9477. def on_options_app2object(self):
  9478. """
  9479. Callback for Options->Transfer Options->App=>Object. Copies options
  9480. from application defaults to the currently selected object.
  9481. :return: None
  9482. """
  9483. self.report_usage("on_options_app2object")
  9484. self.defaults_read_form()
  9485. obj = self.collection.get_active()
  9486. if obj is None:
  9487. self.inform.emit('[WARNING_NOTCL] %s' %
  9488. _("No object selected."))
  9489. return
  9490. for option in self.defaults:
  9491. if option.find(obj.kind + "_") == 0:
  9492. oname = option[len(obj.kind) + 1:]
  9493. obj.options[oname] = self.defaults[option]
  9494. obj.to_form() # Update UI
  9495. class ArgsThread(QtCore.QObject):
  9496. open_signal = pyqtSignal(list)
  9497. start = pyqtSignal()
  9498. if sys.platform == 'win32':
  9499. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  9500. else:
  9501. address = ('/tmp/testipc', 'AF_UNIX')
  9502. def __init__(self):
  9503. super(ArgsThread, self).__init__()
  9504. self.start.connect(self.run)
  9505. def my_loop(self, address):
  9506. try:
  9507. listener = Listener(*address)
  9508. while True:
  9509. conn = listener.accept()
  9510. self.serve(conn)
  9511. except socket.error as e:
  9512. conn = Client(*address)
  9513. conn.send(sys.argv)
  9514. conn.send('close')
  9515. # close the current instance only if there are args
  9516. if len(sys.argv) > 1:
  9517. sys.exit()
  9518. def serve(self, conn):
  9519. while True:
  9520. msg = conn.recv()
  9521. if msg == 'close':
  9522. break
  9523. self.open_signal.emit(msg)
  9524. conn.close()
  9525. # the decorator is a must; without it this technique will not work unless the start signal is connected
  9526. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  9527. @pyqtSlot()
  9528. def run(self):
  9529. self.my_loop(self.address)
  9530. class GracefulException(Exception):
  9531. # Graceful Exception raised when the user is requesting to cancel the current threaded task
  9532. def __init__(self):
  9533. super().__init__()
  9534. def __str__(self):
  9535. return ('\n\n%s' % _("The user requested a graceful exit of the current task."))
  9536. # end of file