FlatCAMApp.py 322 KB

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